自动滚动+方向控制解析

想让dom对象动起来,就要用到setInterval 这个时间函数
方向控制我们就需要设定一个开关top,

最重要的是到达临界点的时候(a==0||a==MAX)要回到最初的临界点

View Code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>New Web Project</title>
        <script type="text/javascript">
            window.onload = function(){
                try {
                    var oLi=document.getElementsByTagName('li'), oLiLen = oLi.length;
                    var a = 0, top = false, timer; //设置开关
                    var obtn1 = document.getElementById('btn1'), obtn2 = document.getElementById('btn2');
                    
                    obtn1.onclick = function(){
                        top = true;
                        scrollB(top);
                    }
                    obtn2.onclick = function(){
                        top = false;
                        scrollB(top);
                    }
                    
                    function scrollB(dir){
                        clearInterval(timer);
                        timer = setInterval(function(){
                            if (dir) {
                                (a == 0) ? a = oLiLen - 1 : a--; //到达第一个的时候后-跳到最后一个从新开始
                            }
                            else {
                                (a == oLiLen - 1) ? a = 0 : a++; //到达最后一个的时候后-跳到第一个从新开始
                            }
                            for (var i = 0; i < oLiLen; i++) {
                                oLi[i].style['background'] = ''; //清空所有样式
                            }
                            
                            oLi[a].style['background'] = 'red'; //给当前保留样式
                            
                        }, 500);
                    }
                } catch(e){
                    alert(111);
                };
            }
        </script>
    </head>
    <body>
        <input type="button" value="top" id="btn1"><input type="button" value="bottom" id="btn2">
        <div id="count">
            <ul>
                <li></li>
                <li></li>
                <li></li>
                <li></li>
                <li></li>
            </ul>
        </div>
    </body>
</html>
原文地址:https://www.cnblogs.com/niubenbit/p/2762832.html