js实现标题无缝向上滚动

用jQuery实现无缝向上滚动挺容易的,想用原生js进行自我学习一下,运用到无缝轮播的思想,有兴趣可以顺便实现一下无缝轮播,有些细节的东西需要注意,以后可能用上,写得不好,各位看官请见谅,话不多说,上代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>demo</title>
</head>
<style>
    *{list-style: none;margin:0;padding: 0;text-decoration: none;}
    .box{
        position: relative;
        width: 20%;
        height: 30px;
        top:50px;
        left:50px;
        overflow-y: hidden;
    }
    #box-ul{
        position: absolute;
        top:0;
        left:0;
    }
    #box-ul li{height:30px;line-height: 30px;}
</style>
<body>
<div class="box">
    <ul id="box-ul">
        <li><a href="#">第一个标题</a></li>
        <li><a href="#">第二个标题</a></li>
        <li><a href="#">第三个标题</a></li>
    </ul>
</div>

</body>
<script>
    window.onload = function () {

        function getStyle(obj,styleName){           //获取元素当前style函数,currentStyle针对ie,getComputedStyle针对其他浏览器
            if(obj.currentStyle){
                return obj.currentStyle[styleName];
            }else{
                return getComputedStyle(obj,false)[styleName];
            }
        }

        function timerFuc() {                       //定时器函数,五秒钟滚动一条数据
            clearInterval(timer);
            timer = setInterval(function () {
                if(i == box.children.length-1) {
                    box.style.top = '0px';
                    i = 0;
                }
                animateTop(box,(++i)*(-30),30);     //此处第一个的30是li标签的高度,修改的时候这里得注意,第二个是speed
            },5000);
        }

        function animateTop(obj,topEnd,speed) {      //滚动函数,object为对象,topEnd为top最终值,speed为滚动速度
            clearInterval(obj.timer);
            obj.timer = setInterval(function () {
                var cur = parseInt(getStyle(obj,'top').slice(0,-2));
                var curspeed = Math.ceil((cur - topEnd)/10);
                obj.style.top = cur - curspeed +'px';
                if(curspeed == 0){
                    clearInterval(obj.timer);
                }
            },speed)
        }


        var i = 0;
        var timer;
        var box = document.getElementById('box-ul');
        var node = document.getElementById('box-ul').firstElementChild.cloneNode(true);     //此处需先克隆节点以便下一步的追加节点操作,类似于jq的clone操作,这地方需要注意,如果不克隆直接获取Element对象会有什么影响,请实践后进行思考。
        box.appendChild(node);
        timerFuc();                 //初始化需执行定时器函数

        box.onmouseover = function () {
            clearInterval(timer);
        };
        box.onmouseout = function () {
            timerFuc();
        }
    };
</script>
</html>

猜你喜欢

转载自blog.csdn.net/yyc135/article/details/69557419
今日推荐