JS實現無縫滾動思路及代碼

JS實現無縫滾動思路及代碼

原理:

1.給ul一個絕對定位使其脫離文檔流,left設置爲0,把圖片塞進ul裏,編寫一個“移動"函數,函數功能能夠使ul的left以一個正速度向右跑動,

2.設置一個定時器,讓"移動"函數每30(參數可變)毫秒執行一次

3.因爲ul的長度會“跑”完,此時可以使ul的content也就是img增加一倍,

oUl.innerHTML +=oUl.innerHTML; 

4.此時因爲ul的content增加,其width也會隨着增大,根據實際項目展示圖片數量可能改動或不確定性,

oUl.style.width = oLi.length*oLi[0].offsetWidth+'px'; 

5.往“移動”函數裏增添代碼。

5.1此時ul向右移動,判斷當ul的offsetLeft>0時,把ul向左拉“一半ul的寬度”,也就是使ul能夠向右一直無限制移動

 

1

2

3

if(oUl.offsetLeft>0){

oUl.style.left = -oUl.offsetWidth/2+'px';

}

5.2當ul向左移動,其offsetLeft跑了ul一半的寬度時,把整個ul拉回至初始的left:0;

 

1

2

3

if (oUl.offsetLeft<-oUl.offsetWidth/2) {

oUl.style.left = 0;

}

html:

<div id="box">
<ul>
<li><a href="#"><img src="1.jpg" /></a></li>
<li><a href="#"><img src="2.jpg" /></a></li>
<li><a href="#"><img src="3.jpg" /></a></li>
<li><a href="#"><img src="4.jpg" /></a></li>
</ul>
</div>

css:

* {margin: 0;padding: 0;}
#box{ width: 480px; height: 110px; border: 1px red solid; margin: 100px auto;overflow: hidden; position: relative; }
#box ul{ position: absolute; left: 0; top: 5px;}
#box ul li{list-style: none; float: left; width: 100px; height: 100px; padding-left: 16px; }
#box ul li img{width: 100px; height: 100px;}

js:

<script>
window.onload = function(){
var oDiv = document.getElementById('div1');
var oUl = oDiv.getElementsByTagName('ul')[0];
var oLi = oUl.getElementsByTagName('li');
var aA = document.getElementsByTagName('a');
var iSpeed = 10; //讓ul開始就具有一個速度走動 
oUl.innerHTML +=oUl.innerHTML; 
oUl.style.width = oLi.length*oLi[0].offsetWidth+'px'; 
aA[0].onclick = function(){
iSpeed = -10;
};
aA[1].onclick = function(){
iSpeed = 10;
};
function fnMove(){
if (oUl.offsetLeft<-oUl.offsetWidth/2) { //負數是因爲ul的left是負數       oUl.style.left = 0;
}
else if(oUl.offsetLeft>0){ oUl.style.left = -oUl.offsetWidth/2+'px'; 
} 
oUl.style.left = oUl.offsetLeft+iSpeed+'px'; //整個ul向右移動 
};
var timer = null; 
clearInterval(timer);
timer = setInterval(fnMove,30);
oUl.onmouseover = function(){
clearInterval(timer);
};
oUl.onmouseout = function(){
timer = setInterval(fnMove,30); //當鼠標移開的時候執行這個定時器
};
};
</script>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章