javascript無限迴圈滾動

jiestyle21發表於2012-04-24
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE html

        PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

    <title></title>

    <style type="text/css">

        * { padding:0; margin:0;}

        body { text-align:center;}

        

        #photo-list {

             /* 3張圖片的寬度(包含寬度、padding、border、圖片間的留白)

                 計算:3*(100+2*2+1*2+9) - 9

                 之所以減去9是第三張圖片的右邊留白

             */

            width:336px;

            /* 圖片的寬度(包含高度、padding、border)

                計算:100+2*2+1*2

            */

            height:106px;

            margin:50px auto; overflow:hidden;

            border:1px dashed #ccc;

        }

        #photo-list ul { list-style:none;}

        #photo-list li { float:left; padding-right:9px;}

        #photo-list img { border:1px solid #ddd; background:#fff; padding:2px;}

    </style>

</head>

<body>

<div id="photo-list">

    <ul id="scroll">

        <li><a href="aaaaaaaaaa"><img src="aaaaaa/logo.jpg" width="100px" height="100px" alt=""/></a></li>
    </ul>

</div>

<script type="text/javascript">

    var id = function(el) {

            return document.getElementById(el);

        },

        c = id('photo-list');

    if(c) {

        var	ul = id('scroll'),

            lis = ul.getElementsByTagName('li'),

            itemCount = lis.length,

            width = lis[0].offsetWidth, //獲得每個img容器的寬度

            marquee = function() {

                c.scrollLeft += 2;

                if(c.scrollLeft % width <= 1){  //當 c.scrollLeft 和 width 相等時,把第一個img追加到最後面

                    ul.appendChild(ul.getElementsByTagName('li')[0]);

                    c.scrollLeft = 0;

                };

            },

            speed = 50; //數值越大越慢



        ul.style.width = width*itemCount + 'px'; //載入完後設定容器長度

        

        var timer = setInterval(marquee, speed);

        c.onmouseover = function() {

            clearInterval(timer);

        };

        c.onmouseout = function() {

            timer = setInterval(marquee, speed);

        };

    };

</script>

</body>

</html>

相關文章