yuxiaoxia28 2015-05-09 07:30 采纳率: 22.2%
浏览 3830

新手求助,我写的js侧边栏上下滑动固定效果,为什么我的一直上下抖动

鼠标滚动得快的时候就出现问题,怎么解决啊?

 <!DOCTYPE html>  
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <style type="text/css">
    body{
        height: 2500px;
    }
        #Div{
            background-color: red;
            width: 100px;
            height: 100px;
            position: absolute;
            right: 0;
        }
        #text{
            width:400px;
            height: 30px;
            position: fixed;
        }
    </style>
    <script type="text/javascript">
        window.onscroll = function(){   
            var div=document.getElementById('Div');
            var scrollTop = document.documentElement.scrollTop||document.body.scrollTop;
            var target=parseInt(scrollTop+(document.documentElement.clientHeight-div.offsetHeight)/2);
            startMove(target);

        }
        function startMove(target){
                var timer=null; 
                var div=document.getElementById('Div'); 
                clearInterval(timer);
                timer=setInterval(function(){                   
                    var iSpeed=(target-div.offsetTop)/8;    
                    iSpeed=iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed);
                    var text = document.getElementById('text'); 
                        text.value="目标为: "+target+" offsetTop: "+div.offsetTop+ " iSpeed:"+iSpeed;

                    if(div.offsetTop==target)
                    {   

                        clearInterval(timer);

                    }
                    else{
                        div.style.top=div.offsetTop+iSpeed+'px';                        
                    }
                },30);  

            }
    </script>
</head>
<body>
    <div id="Div"></div>
    <input type="text" id="text"/>
</body>
</html>
  • 写回答

2条回答

  • pk3995519 2015-05-09 07:47
    关注

    定时器那里调用的有问题。
    在window.onscroll的时候触发了多个定时器。
    你可以多次上下滚动。会发现上下抖动的幅度变的更大。
    还有。建议把定时器对象返回给startMove(target)方法。
    在window.onscroll = function()调用后清除定时器
    window.onscroll = function(){

    var div=document.getElementById('Div');
    var scrollTop = document.documentElement.scrollTop||document.body.scrollTop;
    var target=parseInt(scrollTop+(document.documentElement.clientHeight-div.offsetHeight)/2);
    var timer = startMove(target);
    clearInterval(timer); //在这里加上清除定时器
    }

    评论

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容