问题
An element <div class="">
will fade in when the user scroll down to that div.
I found a solution using a jQuery plugin and another solution to check whether the div is visible on the page. It works.
However, as soon as user scroll to the top of div, it fades in too soon so user doesn't get to see the div fade in. How do I make the div fade-in ONLY if the user scrolls to the bottom of the div so that user can see a nice fade-in effect for the whole div?
回答1:
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.
回答2:
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)
来源:https://stackoverflow.com/questions/5367731/jquery-fade-in-a-div-when-user-scrolls-to-that-div