javascript - jQuery 滚动事件不适用于部分

标签 javascript jquery scroll

我正在尝试使用 jQuery Scroll 事件制作一个简单的滚动 spy ,但失败了。这是我的 JavaScript 部分:

<script>
 $(document).ready(function(){
   $("#credit_card").scroll(function(){
     console.log('OK');
   });
 });
</script>

和 HTML 部分:

<section class="method first-of-group" id="credit_card">
...
</section>

正如您可能已经猜到的,console.log 仅用于测试。该部分位于 div 下,该 div 具有“content”id。如果我更改“内容”id 的 JavaScript 代码,它就可以工作。真的很奇怪。

如果您想观看直播,请访问here .

提前致谢。

最佳答案

阅读评论并真正理解您的意思后,这就是您正在寻找的解决方案。

 $(document).ready(function(){
   $("#content").scroll(function(){

     // when the user scrolls, we want to detect at what section they currently are. 
     // This can be calculated, by comparing the current window scrolltop to the position and height of the section elements.
    var currentTopOffset = $(document).scrollTop();

     $('section').each(function(){
         var min = $(this).offset().top;
         var max = $(this).offset().top + $(this).height();
         if(currentTopOffset > min && currentTopOffset < max){
           // current section
           // do something here, like getting a value from an input type hidden with the section name
         }
     });
   });
 });

我希望这是您正在寻找的东西,或者至少是您入门的东西。

关于javascript - jQuery 滚动事件不适用于部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41325334/

相关文章:

javascript - 如何使用knockout或jquery对数据绑定(bind)列求和?

javascript - 更改滚动 javascript 上 3 个 div 的 css 属性

javascript - 使用 jQuery 检查哪个事件触发了函数?

javascript - 为什么 window.getComputedStyle() 返回属性名称为 "backgroundColor"的对象,但使用属性名称 "background-color"也有效?

javascript - 如何将此 json 转换为 C# 对象

html - 如何在不使用最小宽度或精确固定宽度的情况下使元素水平滚动?

javascript - 绑定(bind)到鼠标滚轮的平滑水平滚动

iphone - 当键盘出现时如何让UITableviewcell向上滚动?

javascript - 在 JS 文件中找不到配置目录

javascript - Rails 远程表单抛出 SyntaxError : Unexpected token :