BxCarousel 是一個設定項目豐富又容易上手的 jQuery 圖片滾動外掛,主要特色有:可指定同時顯示的元素數量、可指定每次滾動的項目數、支援自動播放,以及前後張按鈕控制。
外掛接受任何重複元素,最常見的就是 ul + li:
<ul> <li>first piece of content</li> <li>second piece of content</li> <li>third piece of content</li> <li>fourth piece of content</li> <li>bxCarousel can accept an unlimited number of elements</li> </ul>
$(document).ready(function () {
$('ul').bxCarousel({
display_num: 4, // 同時顯示幾個元素
move: 4, // 每次移動幾個元素
speed: 500, // 動畫毫秒數
margin: 0, // 每個 li 的右邊距(不帶 px)
auto: false, // 是否自動播放
auto_interval: 2000, // 自動播放間隔
auto_dir: 'next', // 自動播放方向
auto_hover: false, // 滑入時是否暫停
next_text: 'next',
next_image: '',
prev_text: 'prev',
prev_image: '',
controls: true // 是否顯示控制鈕
});
});
div.bx_container 與 div.bx_wrap 這類容器元素是外掛動態產生的,為了視覺效果,記得替它們及內部子元素補上 CSS。若使用方向箭頭導航,還要設定 .bx_wrap a.prev 與 .bx_wrap a.next 的背景圖與定位:
.bx_wrap { margin-left: 30px; margin-top: 10px; }
.bx_wrap ul li { text-align: center; float: left; width: 140px;
height: 119px; overflow: hidden; }
.bx_wrap a.prev { position: absolute; top: 45px; left: 5px; text-indent: -999em;
background: url(img/arr_left.gif) no-repeat; }
.bx_wrap a.next { position: absolute; top: 45px; left: 623px; text-indent: -999em;
background: url('img/arr_right.gif') no-repeat; }
.demo { width: 650px; height: 134px; margin: 40px auto; position: relative;
border: 1px solid #d3d3d3; overflow: hidden; }
幾個實務上的提醒:bxCarousel 是無限循環機制,一直按 next 你會發現它會把元素重新排序接龍,這在搭配事件委派時要特別留意。它不只用於圖片,任何 HTML 元素都能放。若開啟 auto,務必確保 speed 小於 auto_interval,否則動畫會互相打斷而顯得卡頓。同類型的滾動外掛還有 bxSlider,體積約 8kb 且 API 更現代,若是新專案可以優先考慮。