jQuery - 检查元素是否可见,淡入淡出 [英] jQuery - check if elements come into view, fade in those that do
问题描述
当我知道要指定哪个元素时,我已经找到了这个问题的答案,但是我正在寻找的方法是检查滚动中是否有具有特定类的ANY元素进入了视图,并对它们进行了修改就像他们所做的那样(例如改变不透明度 - 只有那些进入视野的)。我知道代码可能看起来类似于此,但我无法完成工作:
I have found the answer to this issue when I know which element to specify, but what I am looking for is for a way to check 'on scroll' whether ANY element with a specific class has come into view, and modify them as they do (e.g. change opacity - only those that come into view). I know the code might look something similar to this, but I can't make it work:
jQuery(window).on("scroll", function() {
var difference = jQuery(window).offset().top + jQuery(window).height()/2;
if (difference > jQuery(".makeVisible").offset().top) {
jQuery(this).animate({opacity: 1.0}, 500);
}
});
非常感谢。
注意:存在变量差异是因为我希望元素在到达屏幕中间时可见。
Thank you very much. Note: the variable difference exists because I want elements to become visible as they reach the middle of the screen.
推荐答案
借用滚动后检查元素是否可见和使用jQuery在屏幕上居中DIV 来检查元素位于屏幕的可见中心:
Borrowing from Check if element is visible after scrolling and Using jQuery to center a DIV on the screen to check if the element is in the viewable center of the screen:
function isScrolledIntoView(elem)
{
var centerY = Math.max(0,((jQuery(window).height()-jQuery(elem).outerHeight()) / 2)
+ jQuery(window).scrollTop());
var elementTop = jQuery(elem).offset().top;
var elementBottom = elementTop + jQuery(elem).height();
return elementTop <= centerY && elementBottom >= centerY;
}
然后,我们可以修改您的方法:
We can then modify your approach to:
jQuery(window).on("scroll resize", function() {
jQuery(".makeVisible").each(function(index, element) {
if (isScrolledIntoView(element)) {
jQuery(element).animate({opacity: 1.0}, 500);
}
});
});
这篇关于jQuery - 检查元素是否可见,淡入淡出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!