這是一個最小可用的滑動切換範例:上方一排數字按鈕,下方一個固定尺寸的可視區域,裡面橫向排著十個色塊。點第幾顆按鈕,就把內容列滑到對應位置。
原理不複雜:算出單一項目的實際寬度(width 加上左右 margin),再乘上索引值取負號,當成 left 的目標值丟給 animate 就完成了。初始的 offset = 220 則是為了讓第一個項目預先停在視覺中心。
<html>
<head>
<title>slide demo</title>
<script src="https://code.jquery.com/jquery-1.4.4.min.js"></script>
</head>
<body style="text-align: center;">
<div style="width:540px; margin: 0 auto;">
<div id="button1" class="button" style="float:left;width:50px;margin:2px;background-color:#F00;cursor:pointer;">1</div>
<div id="button2" class="button" style="float:left;width:50px;margin:2px;background-color:#F00;cursor:pointer;">2</div>
<!-- button3 ~ button10 結構相同 -->
</div>
<div style="clear: both"></div>
<div style="width:540px;margin:0 auto;height:400px;position:relative;z-index:999;overflow:hidden;">
<div style="position:relative;padding:0;margin:0 auto;width:100px;">
<div id="list" style="width:1000px;height:400px;position:absolute;z-index:9;left:-220px;">
<div style="width:96px;height:400px;background-color:#004;margin:2px;float:left;color:#FFF;">1</div>
<div style="width:96px;height:400px;background-color:#008;margin:2px;float:left;color:#FFF;">2</div>
<!-- 3 ~ 10 結構相同 -->
</div>
</div>
</div>
</body>
<script>
$(document).ready(function () {
var speed = 1000;
// 單一項目寬度 = width + marginLeft + marginRight
var div_width = $("#list > div:first").width()
+ parseInt($("#list > div:first").css("margin-left"))
+ parseInt($("#list > div:first").css("margin-right"));
var offset = 220;
$(".button").click(function () {
var id = $(this).attr("id").replace("button", "");
var _length = -(id - 1) * div_width - offset;
$("#list").animate({ left: _length + "px" }, speed);
});
});
</script>
</html>
第一,外層容器一定要有 overflow:hidden,否則滑動的內容會溢出來。第二,parseInt 取 margin 時要分別處理左右,寫死一個值在 margin 不同時就會算錯。第三,若項目寬度是百分比或自適應,這段計算邏輯要改成讀 outerWidth(true),jQuery 1.3 之後就有這個方法,比自己加 margin 更省事。第四,快速連點會讓動畫堆疊,正式環境記得在 animate 前加上 .stop(true)。