Why (jQuery) Waypoints “bottom-in-view” doesn't work on hidden elements?

∥☆過路亽.° 提交于 2019-12-23 16:07:27

问题


I was trying to use jQuery & Waypoints (formely jQuery Waypoints) to dynamically show hidden images when a user scrolls down.

I found out that I can quite easily add a waypoint to an element and have the handler triggered when the element is "in view" (with the offset property set at bottom-in-view).

However, trying to use the same property doesn't work on an hidden element: the handler is triggered right after the page is loaded.

E.g.: hiding already-displayed elements when they get in the viewport is easy. (Example 1: jsFiddle):

var waypoints = $('.dynamic').waypoint({
    handler: function (direction) {
        $(this).hide(700);
    },
    offset: 'bottom-in-view'
});

But, what I want to do is the opposite: show a hidden element when we scroll to its position. This next example doesn't work intended as the handler is trigger right after he window.load() event, instead of waiting for the user to scroll down. (Example 2: jsFiddle):

var waypoints = $('.dynamic').waypoint({ // these elements are display: none
    handler: function (direction) {
        $(this).show(700);
    },
    offset: 'bottom-in-view'
});

I found a work-around. I use a empty (but not hidden) div onto which I attach the waypoint. Then, the waypoint gets executed when I scroll-down to aforementioned div. Within the div's handler, I use jQuery to display other elements. (Example 3: jsFiddle):

var waypoints = $('#emptyDiv').waypoint({
    handler: function (direction) {
        $('.dynamic').show(700);
    },
    offset: 'bottom-in-view'
});

However, I am still confused as to why the waypoint is fired right after window.load() when attached to hidden elements. The elements to which the waypoint is attached, despite not being shown, are further down the page.


回答1:


It isn't just 'bottom-in-view'. Every offset fails when the element is hidden with display none. This is covered in detail on the Waypoints debugging guide section on display none elements.

Waypoints works by asking the element where its position is on the page, so that it can calculate where in the scroll it needs to trigger the handler. But display none elements don't live on the page. When asked, those elements report themselves at 0,0.



来源:https://stackoverflow.com/questions/30961414/why-jquery-waypoints-bottom-in-view-doesnt-work-on-hidden-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!