首頁的夥伴 logo 牆要往左持續捲動,而且不能出現斷層。做法是把內容複製一份接在後面,滾到尾端時再把 scrollLeft 拉回起點。
<html>
<head>
<style type="text/css">
#demo {
background: none repeat scroll 0 0 #FFFFFF;
border: 1px solid #98CBFF;
margin-bottom: 10px; margin-left: 5px;
overflow: hidden; padding: 0 0 5px;
width: 948px;
}
#demo img{ border: 3px solid #F2F2F2; }
#indemo{ float: left; width: 800%; }
#demo1{ float: left; }
#demo2{ float: left; }
.box{
border: 1px solid #98CBFF;
float: left; margin: 7px 10px;
overflow: hidden; padding: 5px;
width: 150px;
}
</style>
</head>
<body>
<div id="demo">
<div id="indemo">
<div id="demo1">
<div class="box">
<a href="#"><img src="https://www.example.com/logo.gif" border="0" /></a>
<p>夥伴一</p>
</div>
<div class="box">
<a href="#"><img src="https://www.example.com/logo.gif" border="0" /></a>
<p>夥伴二</p>
</div>
<!-- 更多項目照此結構加上去 -->
</div>
<div id="demo2"></div>
</div>
</div>>
<script>
var speed = 10; // 數字越大速度越慢
var tab = document.getElementById("demo");
var tab1 = document.getElementById("demo1");
var tab2 = document.getElementById("demo2");
tab2.innerHTML = tab1.innerHTML; // 關鍵:複製一份內容
function Marquee(){
if (tab2.offsetWidth - tab.scrollLeft <= 0)
tab.scrollLeft -= tab1.offsetWidth; // 走完一圈就拉回起點
else
tab.scrollLeft++; // 否則繼續往左
}
var MyMar = setInterval(Marquee, speed);
tab.onmouseover = function(){ clearInterval(MyMar); }; // 滑過暫停
tab.onmouseout = function(){ MyMar = setInterval(Marquee, speed); }; // 移開續跑
</script>
</body>
</html>
三個關鍵缺一不可:
一是滑鼠移入要 clearInterval 暫停,否則使用者根本點不到正在跑掉的 logo,這個體驗細節很重要。二是 setInterval 在標籤切到背景時仍會執行,正式環境建議搭配 requestAnimationFrame 並在頁面隱藏時暫停,會省下不少資源。若想雙向或加減速、hover 放大的完整效果,直接採用成熟的跑馬燈套件會省下很多事。