本文分享一個以 jQuery 實作的圖片橫向滾動效果:點擊左右按鈕即可翻動,每次滾動四張圖片,當滾到最後一版後會自動回到第一版,形成循環。
效果如下:
完整程式碼如下:
<!DOCTYPE html>
<html lange="en">
<head>
<title>點擊左右按鈕圖片橫向滾動</title>
<meta charset=utf-8" />
<style type="text/css">
* { margin:0; padding:0;}
body { font-size:12px;}
.box {height:66px; float:left; width:440px; overflow: hidden; position:relative; }
.box li { display:block; float:left; margin-left:5px; margin-right:5px; width:100px; height:70px;background:#BBB;font-size:50px;color:#ccc;line-height:66px;text-decoration:none;text-align:center; cursor:pointer;}
.box li:hover { color:#999; }
.box li.active { background-position:-174px 0; color:#555;cursor:default;}
a.prev, a.next {background:url(https://www.shengyijie.net/images/left_02.png) no-repeat 0 0; display:block;width:23px;height:43px; float:left; margin:15px 0 0 0; cursor:pointer;}
a.next { background-image:url(https://www.shengyijie.net/images/right_02.png)}
.scroll_list{ width:10000em; position:absolute; }
</style>
<!-- 引入 jQuery -->
<script src="https://jt.875.cn/js/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
var page= 1;
var i = 4;// 每版四個圖片
// 向右滾動
$(".next").click(function(){
var v_wrap = $(this).parents(".scroll");
var v_show = v_wrap.find(".scroll_list");
var v_cont = v_wrap.find(".box");
var v_width = v_cont.width();
var len = v_show.find("li").length;
var page_count = Math.ceil(len/i);
if(!v_show.is(":animated")){
if(page == page_count){
v_show.animate({left:'0px'},"slow");
page =1;
}else{
v_show.animate({left:'-='+v_width},"slow");
page++;
}
}
});
// 向左滾動
$(".prev").click(function(){
var v_wrap = $(this).parents(".scroll");
var v_show = v_wrap.find(".scroll_list");
var v_cont = v_wrap.find(".box");
var v_width = v_cont.width();
var len = v_show.find("li").length;
var page_count = Math.ceil(len/i);
if(!v_show.is(":animated")){
if(page == 1){
v_show.animate({left:'-='+ v_width*(page_count-1)},"slow");
page =page_count;
}else{
v_show.animate({left:'+='+ v_width},"slow");
page--;
}
}
});
});
</script>
</head>
<body>
<div class="scroll" style="margin:0 auto;width:550px;">
<a class="prev" href="#"></a>
<div class="box">
<div class="scroll_list">
<ul>
<li>1</li><li>2</li><li>3</li><li>4</li>
<li>5</li><li>6</li><li>7</li><li>8</li>
<li>9</li><li>10</li><li>11</li><li>12</li>
<li>13</li><li>14</li><li>15</li><li>16</li>
</ul>
</div>
</div>
<a class="next" href="#"></a>
</div>
</body>
</html>
核心概念在於:透過 animate() 改變外層容器的 left 位移,並以 page 變數記錄目前頁碼;當抵達最後一頁再按下一頁時,就將位移歸零回到初始位置,藉此達成無縫循環的效果。