注册 登录
编程论坛 JavaScript论坛

div一直跳

小棉袄 发布于 2015-03-24 16:20, 418 次点击
<style>
#div1{width:100px;height:150px;background:red;position:absolute;right:0; bottom:0;}
</style>
<script>
window.onscroll=function ()
{
    var odiv=document.getElementById('div1');
    var scrollTop=document.documentElement.scrollTop||document.body.scrollTop
    startmove(document.documentElement.clientHeight-odiv.offsetHeight+scrollTop);
    //odiv.style.top=document.documentElement.clientHeight-odiv.offsetHeight+scrollTop+'px';
    var timer=null;
    function startmove(iTarget)
    {
        var odiv=document.getElementById('div1');
        clearInterval(timer);
        timer=setInterval(function (){
            var speed=(iTarget-odiv.offsetTop)/6;
            speed=speed>0?Math.ceil(speed):Math.floor(speed);
            if(odiv.offsetTop==iTarget)
            {
                clearInterval(timer);   
            }
            else
            {
                odiv.style.top=odiv.offsetTop+speed+'px'   
            }
        },30)   
    }
}

</script>
</head>

<body style="height:2000px;">
<div id="div1">

</div>
</body>
</html>
1 回复
#2
冰镇柠檬汁儿2015-03-25 21:13
你程序的逻辑本身就有问题
首先,startmove写在了onscroll事件里面,每次都要重新定义,不合乎逻辑,虽然这样写,不会有什么错误,但建议写在事件的外面。
其次,貌似onscroll每次调用,才会执行startmove函数里的setInterval,但是onscroll事件的调用是非常多的,每改变1个像素都有可能产生调用,这样就造成了之前的setInterval和之后的setInterval连续并交叉执行。
结论是,不抖才怪

告诉我你想实现什么效果,看你这段代码的水平,不太适合过深的方法解决这个问题
1