为了账号安全,请及时绑定邮箱和手机立即绑定

为什么jquery利用animate滚动scrollTop之后被锁定就滚动不了了?

为什么jquery利用animate滚动scrollTop之后被锁定就滚动不了了?

admop 2017-10-12 20:40:27
求帮忙解答,谢谢! <html> <head> <meta charset="utf-8"> <script src="j.js"></script> <style> * { padding:0; margin:0; border:0; } .one,.two,.three { display:block; } .one { width:1px; height:1px; background-color:#f00; } .tow { background-color:#00f; } .three { background-color:#cecece; } </style> </head> <body> <!-- jquery自写滚动屏幕 --> <div class="one">one</div> <div class="two">two</div> <div class="three"></div> <script> $(document).ready(function(){ //获取当前文档的宽 高 nowWidth = $(window).width(); nowHeight = $(window).height(); //获取大的背景div one = $(".one"); two = $(".two"); three = $(".three"); <!-- alert(typeof(nowHeight)); --> //开始设置宽度高度为当前屏幕高度 one.css({"height":nowHeight,"width":nowWidth}); two.css({"height":nowHeight,"width":nowWidth}); three.css({"height":nowHeight,"width":nowWidth}); //开始监听滚动栏 //准备获取文档 var ht = $("document,html,body"); $(document).scroll(function(){ //获取当前滚动条距离文档高度 var top = $(document).scrollTop(); //如果高度 > 1  移动到第二屏 针对第一屏 if(top > 2 && top < nowHeight){ //设置滚动条高度为第一屏高度 ht.animate({"scrollTop":nowHeight},1000); } if(top > nowHeight + 2 && top < (nowHeight * 2)){ ht.animate({"scrollTop":nowHeight *2},1000); } }) }) </script> </body> </html>
查看完整描述

2 回答

?
林逸舟丶

TA贡献124条经验 获得超28个赞

对你代码做了补分修改:

<script>
$(document).ready(function(){
 
    //获取当前文档的宽 高
    nowWidth = $(window).width();
    nowHeight = $(window).height();

    //获取大的背景div
    one = $(".one");
    two = $(".two");
    three = $(".three");

    //开始设置宽度高度为当前屏幕高度         
    one.css({"height":nowHeight,"width":nowWidth});
    two.css({"height":nowHeight,"width":nowWidth});
    three.css({"height":nowHeight,"width":nowWidth});
     
    //打印nowHeight
    console.log(nowHeight);
    // 获取body,用以获取滚动条高度scrollTop
    var ht = $("body");

    // 立个flag让函数只执行一次
    var flag=true;	 

    // 开始监听滚动栏
    $(document).scroll(function(){
        //获取当前滚动条距离文档高度
        var top = $(document).scrollTop();
        //如果高度 > .div1的1/5高度  自动移动到第二屏
        if(top > nowHeight/5 && top < nowHeight && flag)
        {
        	ht.animate({"scrollTop":nowHeight},1000,function(){console.log($(document).scrollTop());});
        	flag=false;
        }
        
        if(top > (nowHeight+nowHeight/5) && top < (nowHeight * 2) && flag)
    	{
        	ht.animate({"scrollTop":nowHeight *2},1000);
        	flag=false;
        }            
    })        
})     
</script>

这段代码运行后,滚动条不会卡住。

所以答案即是:

“所谓的滚动条卡住”,是因为你每次重新滚动时,再一次触发了源代码中:

if(top > 2 && top < nowHeight){

这个条件,所以会重新移动,造成“卡住”的现象。

查看完整回答
反对 回复 2017-10-13
?
MarlboroKay

TA贡献189条经验 获得超236个赞

因为你的判断条件有问题:

第二个if 里面同时满足第一个条件,当然一直停留在第一个if里的状态了


查看完整回答
反对 回复 2017-10-13
  • 2 回答
  • 0 关注
  • 3558 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信