無縫滾動的精髓只有一句話:每滾完一格,就把第一個項目搬到最後面。這樣 DOM 裡永遠有內容填著,視覺上就不會出現斷層。
<!DOCTYPE html>
<html>
<head lang="zh-Hant">
<meta charset="UTF-8">
<title>無縫滾動</title>
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<style>
* { margin: 0; padding: 0; }
li { list-style: none; }
.content {
width: 1020px;
height: 112px;
overflow: hidden;
border: #4e83c2 solid 1px;
margin: 50px auto;
}
.content ul { width: 1020px; height: 100px; }
.content ul li {
float: left;
width: 100px;
height: 100px;
border: #ccc solid 1px;
display: block;
margin: 5px;
}
</style>
</head>
<body>
<div class="content">
<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>
</ul>
</div>
<script>
function scroll() {
$(".content ul").animate({ "margin-left": "-110px" }, function() {
$(".content ul li:eq(0)").appendTo($(".content ul"));
$(".content ul").css({ "margin-left": 0 });
});
}
setInterval(scroll, 1000);
</script>
</body>
</html>
overflow: hidden 讓容器只顯示可見範圍,多餘的內容被裁掉。li 用 float: left 排成一列,寬度加上左右 margin 各 5px,所以每一格實際佔 110px。animate() 把整個 ul 往左推 110px,正好一格。// 向左(範例預設)
$(".content ul").animate({ "margin-left": "-110px" }, function() {
$(".content ul").css({ "margin-left": 0 });
});
// 向上
$(".content ul").animate({ "margin-top": "-105px" }, function() {
$(".content ul").css({ "margin-top": 0 });
});
// 向右:先往右推,再把「最後一個」搬到最前面
$(".content ul").animate({ "margin-left": "110px" }, function() {
$(".content ul li:last").prependTo($(".content ul"));
$(".content ul").css({ "margin-left": 0 });
});
向右滾動時搬動的對象必須改成最後一個元素並用 prependTo,否則會出現空白。
把位移量改成 N 倍即可,但搬動的數量也要對應增加:
function scrollN(n) {
$(".content ul").animate({ "margin-left": "-" + (110 * n) + "px" }, function() {
for (var i = 0; i < n; i++) {
$(".content ul li:eq(0)").appendTo($(".content ul"));
}
$(".content ul").css({ "margin-left": 0 });
});
}
使用者想點擊某個項目時,滾動不能繼續:
var timer = setInterval(scroll, 1000);
$('.content').hover(
function() { clearInterval(timer); },
function() { timer = setInterval(scroll, 1000); }
);
範例把 110px 寫死,一旦調整 CSS 就會失效。建議動態量測:
var step = $(".content ul li").outerWidth(true); // 含 margin
連續快速觸發會讓動畫堆積。加上 .stop(true) 可清掉尚未執行的動畫:
$(".content ul").stop(true).animate({ ... });
單純的跑馬燈用 CSS animation 就夠了,不必 JS:
@keyframes marquee {
from { transform: translateX(0); }
to { transform: translateX(-110px); }
}
.content ul { animation: marquee 1s linear infinite; }
若需要無限循環,把內容複製一份接在后面,讓 animation 在複本起點重啟即可,這也是目前多數輪播套件(Swiper、slick)採用的思路。