這是一個用 jQuery 寫的水平圖片輪播:左右兩個按鈕控制捲動方向,每按一次把一張圖移到另一端,形成無止境循環;最後一個參數傳 true 時會自動播放,滑鼠移入則暫停。
複製代碼 代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>圖片輪播</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>
<style type="text/css">
body,ul,li { padding:0; margin:0}
ul,li { list-style:none}
.img-scroll { position:relative; margin:20px auto; width:440px;}
.img-scroll .prev,.img-scroll .next { position:absolute; display:block; width:50px; height:100px; background-color:#000;
top:0; color:#FFF; text-align:center; line-height:100px}
.img-scroll .prev { left:0}
.img-scroll .next { right:0}
.img-list { position:relative; width:320px; height:100px; margin-left:60px; overflow:hidden}
.img-list ul { width:9999px;}
.img-list li { float:left; display:inline; width:100px; margin-right:10px; height:100px; background-color:#BDBDDF; text-align:center; line-height:100px;}
</style>
</head>
<body>
<div class="img-scroll">
<span class="prev">prev</span>
<span class="next">next</span>
<div class="img-list">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
</div>
</div>
<script type="text/javascript">
function DY_scroll(wraper,prev,next,img,speed,or)
{
var wraper = $(wraper);
var prev = $(prev);
var next = $(next);
var img = $(img).find('ul');
var w = img.find('li').outerWidth(true);
var s = speed;
next.click(function()
{
img.animate({'margin-left':-w},function()
{
img.find('li').eq(0).appendTo(img);
img.css({'margin-left':0});
});
});
prev.click(function()
{
img.find('li:last').prependTo(img);
img.css({'margin-left':-w});
img.animate({'margin-left':0});
});
if (or == true)
{
ad = setInterval(function() { next.click();},s*1000);
wraper.hover(function(){clearInterval(ad);},function(){ad = setInterval(function() { next.click();},s*1000);});
}
}
DY_scroll('.img-scroll','.prev','.next','.img-list',3,false);
</script>
</body>
</html>
整個效果不靠「算總寬度再平移一大段」,而是每次只位移一格 w(用 outerWidth(true) 取得,含 margin,所以間距不會跑掉)。向右翻時,動畫結束的 callback 把第一個 li 搬到 ul 的最後並把位移歸零;向左翻時先反向操作——把最後一個 li 插到最前面,此時 ul 已經往左多了一格,再動畫回到 0。因為永遠只移動一格且立刻歸位,所以能無限循環下去,不需要複製整份 DOM。
自動播放則是每隔 speed 秒觸發一次 next 的 click,並在 hover 時清掉計時器、移開後重新啟動,避免使用者正在看圖時被強制捲動。