JQuery fade-in a div when user scrolls to that div

只谈情不闲聊 提交于 2019-11-27 20:16:21

you mentioned that you used a jQuery plugin, i don't know if you have tried jQuery waypoints plugin, you can do it using this plugin easily by passing an offset option to the plugin as follows:

// by default your element will be hidden
$('div').hide();
// call waypoint plugin
$('div').waypoint(function(event, direction) {
    // do your fade in here
    $(this).fadeIn();
}, {
   offset: function() {
       // The bottom of the element is in view
       return $.waypoints('viewportHeight') - $(this).outerHeight();
    }
});

offset : Determines how far the top of the element must be from the top of the browser window to trigger a waypoint. It can be a number, which is taken as a number of pixels, a string representing a percentage of the viewport height, or a function that will return a number of pixels.

so on the previous example, your div won't fade in unless it's in the middle of the page.

This javascript code is possibly similar to what you currently use, the only difference being the offset used, which is simply the target element's offset().top() + the element's height(). The demo code fades in several <li> elements as the bottom of the elements come into view.

tiles = $("ul#tiles li").fadeTo(0,0);

$(window).scroll(function(d,h) {
    tiles.each(function(i) {
        a = $(this).offset().top + $(this).height();
        b = $(window).scrollTop() + $(window).height();
        if (a < b) $(this).fadeTo(500,1);
    });
});

Demo: jsfiddle.net/Marcel/BP6rq (fullscreen)

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