【问题标题】:How to detect page scroll to a certain point in jQuery?如何在jQuery中检测页面滚动到某个点?
【发布时间】:2011-02-18 01:46:28
【问题描述】:

想象一下这是我的页面:

<p>hello</p>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<p class="myPara">My Paragraph</p>

当用户向下滚动到具有“myPara”类的段落而不是在此之前,我如何才能提醒消息?

【问题讨论】:

    标签: jquery


    【解决方案1】:

    怎么样:

    var target = $(".myPara").offset().top;
    var interval = setInterval(function() {
        if ($(window).scrollTop() >= target) {
            alert("made it!");
            clearInterval(interval);
        }
    }, 250);
    

    这是一个例子:http://jsfiddle.net/andrewwhitaker/24M3n/1/

    您可能很想将事件处理程序附加到窗口滚动事件,但John Resig advises against it(向下滚动到“最佳实践”)。

    更新As @AbdulJabbarWebBestow points out,每 250 毫秒不必要地运行一个函数可能是个坏主意。这是一个更新后的示例,它仅在用户第一次滚动后 250 毫秒运行一次:

    var target = $(".mypara").offset().top,
        timeout = null;
    
    $(window).scroll(function () {
        if (!timeout) {
            timeout = setTimeout(function () {
                console.log('scroll');            
                clearTimeout(timeout);
                timeout = null;
                if ($(window).scrollTop() >= target) {
                    alert('made it');
                }
            }, 250);
        }
    });
    

    示例: http://jsfiddle.net/24M3n/858/

    【讨论】:

    • 使用 setInterval 不适合这种操作。只需使用 Reigel 的回答所解释的 jQuery 滚动侦听器
    • @StefanoPochet:实际上,这是使用setInterval完美时间。查看我在答案中链接到的文章,了解为什么您不想直接附加到.scroll
    • 阅读文章。很高兴知道这一点,现在我认为您的答案是正确的。但我仍然会说,在这种特定情况下,更简洁、响应更快的解决方案是使用 onScroll 并将选择器指令简单地放在 onScroll 代码块之外。像这样的东西: var myTargetDivPositionTop = $(".myPara").offset().top; $(window).scroll(function(){ if( $(window).scrollTop() > myTargetDivPositionTop ){ doMyStuff() } }
    • @StefanoPochet 我认为这不是一个好的答案,因为这个函数会在我们甚至没有滚动的时候持续触发事件。像这样 setInterval(function() {console.log('Hello World'); 放入 console.log('Hello World'); 就可以看到,这是一个资源消耗的任务。跨度>
    • @SteveMcLeod 现在可能不会。也许是 6.5 年前的事了?也许现在发布一个更相关的答案会对您有所帮助。
    【解决方案2】:
    $(window).scroll(function(){
        console.log($('#myPara').offset().top < $(this).height() + $(this).scrollTop());
    });
    

    【讨论】:

    • 最适合我。非常感谢。
    • 简直完美!
    【解决方案3】:

    我一直在考虑附加滚动事件的问题(@AndrewWhitaker 指出),我最后的想法是没有必要每 x 秒添加一个 scoll 事件处理程序,因为你可以只执行一个 @ 987654321@ 并在回调中检查是否应显示警报。例如:

    var showMessageInterval = window.setInterval(showMessageIfNeeded, 500);
    // you could adjust the interval to the animation duration of the 
    // message showing. In this way, the delay will be more "natural"
    

    showMessageIfNeeded 回调将检查 scrollTop 值并在需要时显示消息。如果显示该消息,则必须清除 setInterval 以避免下一次执行:

    function showMessageIfNeeded() {
        var scrollTop = $(window).scrollTop();
        var targetTop = $(".myPara").offset().top;
        if (scrollTop > targetTop) {
            alert('Show message');
            window.clearInterval(showMessageInterval);
        }
    }
    

    【讨论】:

      【解决方案4】:

      您可以使用 scrollspy jquery 插件来做到这一点。 https://github.com/thesmart/jquery-scrollspy

      $('.myPara').on('scrollSpy:enter', function() {
          console.log('enter:', $(this).attr('id'));
      });
      
      $('.myPara').on('scrollSpy:exit', function() {
          console.log('exit:', $(this).attr('id'));
      });
      
      $('.tile').scrollSpy();
      

      【讨论】:

        【解决方案5】:

        将页面滚动位置与您的元素顶部位置进行比较,而不是调用您的函数。

        jQuery

        $(document).on('scroll', function() {
          if ($(this).scrollTop() >= $('.myPara').position().top) {
            console.log('Reached');
          }
        })
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
        <p>hello</p>
        <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
        <p class="myPara">My Paragraph</p>
        <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>

        ES6(纯 JS,无 jQuery)

        var target = document.querySelector('.myPara');
        
        document.addEventListener('scroll', () => {
          if (window.scrollY >= target.getBoundingClientRect().top) {
            console.log('Reached');
          }
        })
        <p>hello</p>
        <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
        <p class="myPara">My Paragraph</p>
        <br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>

        【讨论】:

          猜你喜欢
          • 2012-04-03
          • 2012-06-26
          • 2015-06-28
          • 1970-01-01
          • 2013-12-02
          • 1970-01-01
          • 2013-06-30
          • 2020-01-19
          • 2021-08-21
          相关资源
          最近更新 更多