【问题标题】:how to detect if scroll is happening within certain element如何检测是否在某个元素内发生滚动
【发布时间】:2021-04-05 07:24:16
【问题描述】:

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

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 的 div 内时,我想执行某些代码
  • 所以你的代码说当我在这个元素中滚动时我正在检查滚动条是向上还是向下移动.....问题是如果你有多个元素,你共享同一个全局变量。

标签: javascript html jquery scroll


【解决方案1】:

编辑:

scrollTop 为您提供元素而非页面的滚动条的当前位置。
因此,如果他没有滚动条,它将为 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>

【讨论】:

  • 我认为我的问题是 div 项没有溢出。目前我检查了windows上的滚动和一个布尔值,如果指针在那个div上。无论如何感谢您的回答
猜你喜欢
  • 1970-01-01
  • 2012-11-28
  • 1970-01-01
  • 2020-07-05
  • 1970-01-01
  • 2010-10-03
  • 1970-01-01
  • 2012-10-24
  • 2014-09-30
相关资源
最近更新 更多