很多輪播範例只能在頁面上放一個,因為id、計時器、索引全是全域變數。這個版本把邏輯包進建構函式裡,用命名空間隔開狀態,因此可以同時在頁面放好幾組、各自帶不同參數。
// 簡易的陣列遍歷工具
var $o = new Object();
$o.base = {
e: function(a, f){
for (var i=0, j=a.length; i<j; i++){ f.call(a[i], i); }
}
};
$o.slide = function (id, arg){
var arg = arg || {},
t = document.getElementById(id),
a = t.getElementsByTagName("a"), // 每張投影片就是一個 <a><img>
lis = [],
cl = arg.color || '#f30', // 主題色
ctm = arg.time * 1000 || 2000, // 自動切換間隔(秒)
w = t.clientWidth,
h = t.clientHeight,
b = ['<ul style="margin:0;padding:0;list-style:none;display:block;position:absolute;bottom:10px;right:10px;">'],
index = 0, $ = null;
容器會被設成 overflow:hidden; position:relative,所有投影片則是靠改變 marginTop 做垂直位移,一次只露出畫面高度 H 的那一張。
function change(i){
if (!!$) { clearTimeout($); }
index = !isNaN(i) ? i : index + 1;
if (index >= a.length) { index = 0; } // 迴圈播放
// 切換下方指示按鈕的高亮狀態
$o.base.e(lis, function(k){
if (k == index) { c(1, this); } else { c(0, this); }
});
var to = - index * h; // 目標位移量
if (a[0].offsetTop == to) { return; } // 已在目標位置就不動
if (!!$) { clearInterval($); }
$ = setInterval(function(){
var ot = a[0].offsetTop;
// 每次只走剩餘距離的 20%,越接近越慢,形成緩動效果
v = Math[to < ot ? 'floor' : 'ceil']((to - ot) * 0.2);
if (ot == to) { clearInterval($); $ = null; st(); }
ot += v;
a[0].style.marginTop = ot + "px";
}, 30);
}
(to - ot) * 0.2 是這個範例最關鍵的一行:每幀只走剩餘距離的五分之一,自然形成「先快後慢」的緩動(easing),不需要額外的 easing 函式表。搭配 floor/ceil 依方向取整,才能確保最終一定會等於目標值、不會無限接近卻永遠差一點。
function c(b, o){ // 切換按鈕配色
o.style.backgroundColor = !!b ? cl : "#fff";
o.style.color = !!b ? "#fff" : cl;
}
function st(){ // 排下一次自動切換
if (!!$) clearTimeout($);
$ = setTimeout(function(){ change(); }, ctm);
}
// 初始化:產生每張投影片的樣式與對應的數字按鈕
$o.base.e(a, function(n){
this.style.display = "block";
with(this.firstChild.style){ borderWidth='0'; width=w+'px'; height=h+'px'; }
b.push('<li style="...cursor:pointer;">' + (n+1) + '</li>');
});
b.push('</ul>');
t.innerHTML += b.join("");
lis = t.getElementsByTagName("li");
$o.base.e(lis, function(n){
if (n == index) c(1, this);
this.onmouseover = function(){ if (n != index) change(n); };
});
st();
<div id="aa" style="width:402px;height:228px;">
<a href="javascript:alert('1')"><img src="/images/1.jpg"></a>
<a href="javascript:alert('2')"><img src="/images/2.jpg"></a>
<a href="###"><img src="/images/3.jpg"></a>
</div>
<script>new $o.slide("aa");</script>
<div id="bb" style="width:402px;height:228px;">/* ... */</div>
<script>new $o.slide("bb", {color:'#000', time:0.2});</script>
<div id="cc" style="width:402px;height:228px;">/* ... */</div>
<script>new $o.slide("cc", {color:'green'});</script>
三組輪播各自帶不同主題色與切換速度,彼此不互相干擾,這就是「可重複呼叫」的意思。
with 語法在嚴格模式下不能用,改成逐一指定屬性即可。javascript: 協定連結不便於無障礙與 SEO,建議改用 href="#" 搭配事件綁定並 preventDefault()。alt 文字。這個範例最值得學的是「用建構式封裝狀態」與「以剩餘距離比例做緩動」這兩個技巧,兩者在各種自製元件裡都能重複利用。