javascript無縫水平滾動實例

首先看源代碼:

<html>
<head>
<title>無縫滾動實例--左右滾動</title>
<style type="text/css">
img { border:none; margin:0px; }
#demo { width:600px; overflow:hidden; height:120px; border:solid 3px red; }
#demo1 { float:left; width:766px; }
#demo2 { float:left; width:766px; }

#clear { clear:both; }
</style>
</head>

<body>
<div id="demo">
<div id="marquee">
   <div id="demo1">
    <img src="images/js01.jpg" width="120" height="120" />
    <img src="images/js02.jpg" width="120" height="120" />
    <img src="images/js03.jpg" width="120" height="120" />
    <img src="images/js04.jpg" width="120" height="120" />
    <img src="images/js05.jpg" width="120" height="120" />
    <img src="images/js06.jpg" width="120" height="120" />
   </div>

   <div id="demo2"></div>
</div>
</div>

<div id="clear">&nbsp;</div>

<script type="text/javascript">
var speed = 10;
var demo = document.getElementById("demo");
var demo1= document.getElementById("demo1");
var demo2= document.getElementById("demo2");
var marquee = document.getElementById("marquee");

demo2.innerHTML = demo1.innerHTML;
marquee.style.width = demo1.offsetWidth * 2;
function fMarquee()
{
if(demo2.offsetWidth - demo.scrollLeft <= 0) { demo.scrollLeft -= demo2.offsetWidth; }
else { demo.scrollLeft++; }
}

var myMarquee = setInterval(fMarquee,speed);
demo.onmouseover = function() { clearInterval(myMarquee); }
demo.onmouseout = function() { myMarquee = setInterval(fMarquee, speed); }
</script>
</body>

</html>

 

代碼結束。

 

基本原理與垂直滾動效果是一樣的,只不過,在佈局的時候發生了一點小小的改變。

他的結構應該是這樣的

<div id="demo">
<div id="marquee">
    <div id="demo1">
      content...
    </div>
    <div id="demo2"></div>
</div>
</div>

 

用demo包含所有的內容。而且demo必須制定寬度和高度,且overflow:hidden;必須加上。其實demo指定的是滾動框的高度和寬度。

用marquee包含所有的內容,與demo不同的是,marquee的寬度是剛好夠放下demo1與demo2的內容的(橫向排列,所以需要float:left; 而且寬度要設置。)

接下來的是用javascript將marquee的寬度設置爲兩倍demo1的寬度。marquee.style.width = demo1.offsetWidth * 2; 以確保demo1與demo2是橫向排列的。

在滾動時,若demo的scrollLeft已經到超過了demo2的寬度,說明應該重新開始了。用

if(demo2.offsetWidth - demo.scrollLeft <= 0) { demo.scrollLeft -= demo2.offsetWidth; }
else { demo.scrollLeft++; }

最後用var myMarquee = setInterval(fMarquee, speed) 重複滾動。

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