[英]how to detect if scroll is happening within certain element
I wanted to detect if the pointer scroll is happening within a certain element and then do certain actions.我想检测指针滚动是否发生在某个元素内,然后执行某些操作。 I've tried this code but it seems to not working:我已经尝试过这段代码,但它似乎不起作用:
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;
});
can you help me understand what I am doing wrong?你能帮我理解我做错了什么吗?
Thank you!谢谢!
EDIT:编辑:
scrollTop
gives you the current position of the scroll bar of the element not of the page. scrollTop
为您提供非页面元素滚动条的当前 position。
So if he hasn't scroll bar it will be 0.:因此,如果他没有滚动条,它将为 0。:
or if the element is not scrollable, this number will be 0.或者如果元素不可滚动,则此数字将为 0。
and the same for .scroll()
if the element hasn't scroll bar it will never occur.如果元素没有滚动条,则.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.