简体   繁体   English

每次使用 jQuery 看到某个元素时如何做某事?

[英]How to do something everytime a certain element is in view using jQuery?

Right now every time the user reaches the bottom of my page I update the url hash using this code:现在,每次用户到达我的页面底部时,我都会使用以下代码更新 url hash:

var new_page_value = 1;
$(window).scroll(function() {
    if($(window).scrollTop() == $(document).height() - $(window).height()) {
        new_page_value += 1;
        window.location.hash = 'page-' + new_page_value;
    }
});

How can I do the same when the user scrolls past any of the divs with the class "page" in the code below?当用户在下面的代码中滚动到带有 class “页面”的任何 div 时,我该如何做同样的事情? For example if the user scrolls into view the 1st one the hash should be updated to #page-1 but as soon as they scroll into view the 2nd one the hash should be updated to #page-2 and so on.例如,如果用户滚动到第一个视图中,则 hash 应更新为#page-1,但一旦他们滚动到第二个视图中,hash 应更新为#page-2,依此类推。 And if they scroll back to the first the hash should once again be updated to #page-1.如果他们滚动回到第一个,hash 应该再次更新为#page-1。 Basically the hash should update based on whatever div is in view.基本上 hash 应该根据视图中的任何 div 进行更新。

<div class="page" data-page-num="1"></div>

<br /><br /><br /><br /><br /><br /><br /><br /><br />

<div class="page" data-page-num="2"></div>

<br /><br /><br /><br /><br /><br /><br /><br /><br />

<div class="page" data-page-num="3"></div>

This code may help, but it might be a little intensive on the client side.此代码可能有所帮助,但在客户端可能有点密集。

var new_page_value = 1;
$(window).scroll(function() {
    $(".page").each(function() {
        var position = $(this).position();
        if($(window).scrollTop() == position.top) {
            new_page_value += 1;
            window.location.hash = 'page-' + new_page_value;
        }
    });

    if($(window).scrollTop() == $(document).height() - $(window).height()) {
        new_page_value += 1;
        window.location.hash = 'page-' + new_page_value;
    }
});

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

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