繁体   English   中英

如何检测是否在某个元素内发生滚动

[英]how to detect if scroll is happening within certain element

我想检测指针滚动是否发生在某个元素内,然后执行某些操作。 我已经尝试过这段代码,但它似乎不起作用:

var lastScrollTop = 0;
    $(".class-name").scroll(function(event){
       var st = $(this).scrollTop();
       if (st > lastScrollTop){
           console.log("scroll down");
       } else {
          console.log("scroll up");
       }
       lastScrollTop = st;
    });

你能帮我理解我做错了什么吗?

谢谢!

编辑:

scrollTop为您提供非页面元素滚动条的当前 position。
因此,如果他没有滚动条,它将为 0。:

或者如果元素不可滚动,则此数字将为 0。

如果元素没有滚动条,则.scroll()也一样,它将永远不会发生。

 var lastScrollTop = 0; $(".class-name").scroll(function(event){ var st = $(this).scrollTop(); if (st > lastScrollTop){ console.log("scroll down"); } else { console.log("scroll up"); } lastScrollTop = st; });
 .class-name{ width:100px; height:200px; overflow:auto; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="class-name">hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello hello </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM