繁体   English   中英

jQuery滚动事件不适用于本节

[英]jQuery Scroll Event Not Working With Section

我正在尝试使用jQuery Scroll事件制作一个简单的scrollspy,但是失败了。 这是我的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具有“内容” ID。 如果我将JavaScript代码更改为“内容” ID,则它可以正常工作。 真的很奇怪

如果您想现场观看,请访问这里

提前致谢。

阅读评论并真正理解您的意思之后,这就是您想要的解决方案。

 $(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
         }
     });
   });
 });

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

暂无
暂无

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

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