当用户滚动到该 div 时,JQuery 淡入该 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5367731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery fade-in a div when user scrolls to that div
提问by ForeverNights
An element <div class="">
will fade in when the user scroll down to that div.
<div class="">
当用户向下滚动到该 div 时,元素将淡入。
I found a solution using a jQuery plugin and another solution to check whether the div is visible on the page. It works.
我找到了一个使用 jQuery 插件的解决方案和另一个检查 div 在页面上是否可见的解决方案。有用。
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?
然而,一旦用户滚动到 div 的顶部,它就会过早地淡入,所以用户看不到 div 淡入。如果用户滚动到底部,我如何使 div 淡入div 以便用户可以看到整个 div 的漂亮淡入效果?
采纳答案by Anas Nakawa
you mentioned that you used a jQuery plugin, i don't know if you have tried jQuery waypointsplugin, you can do it using this plugin easily by passing an offset option to the plugin as follows:
您提到您使用了 jQuery 插件,我不知道您是否尝试过jQuery 航路点插件,您可以通过向插件传递偏移选项来轻松使用此插件,如下所示:
// 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.
offset:确定元素顶部必须离浏览器窗口顶部多远才能触发航点。它可以是一个数字,它被视为一个像素数,一个表示视口高度百分比的字符串,或者一个将返回多个像素的函数。
so on the previous example, your div won't fade in unless it's in the middle of the page.
所以在前面的例子中,你的 div 不会淡入,除非它在页面的中间。
回答by Marcel
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.
这段 javascript 代码可能与您当前使用的类似,唯一的区别是使用的偏移量,它只是目标元素的offset().top()
+ 元素的height()
. 当<li>
元素的底部进入视图时,演示代码逐渐淡入几个元素。
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);
});
});