我遇到了以下 fiddle ,它让元素在到达顶部时一个一个地淡出文档。
通过执行javascript:
$(window).scroll(function () {
$('[id^="box"]').each(function () {
if (($(this).offset().top - $(window).scrollTop()) < 20) {
$(this).stop().fadeTo(100, 0);
} else {
$(this).stop().fadeTo('fast', 1);
}
});
});
只有它适用于整个窗口,我希望它适用于 div 标签。所以我修改了 fiddle 以在其中添加 div 测试和所有其他 div,然后修改 javascript 以获取 div 而不是窗口:
$("#test").scroll(function () {
$('[id^="box"]').each(function () {
if (($(this).offset().top - $("#test").scrollTop()) < 20) {
$(this).stop().fadeTo(100, 0);
} else {
$(this).stop().fadeTo('fast', 1);
}
});
});
http://jsfiddle.net/JdbhV/1692/
但现在它们消失得太快了,当它们到达 div 的顶部时就消失了。
有人指出这里出了什么问题吗?
最佳答案
The .offset() method allows us to retrieve the current position of an element relative to the document.
滚动窗口不会改变元素在文档中的位置,但是在另一个元素内滚动元素会。这会导致偏移位置发生变化,从而导致检查框是否位于 ScrollView 的顶部。
尝试使用 .position()获取相对于父级的位置的方法。
$("#test").scroll(function () {
$('[id^="box"]').each(function () {
//When the top of the square goes above the top of the scroll element, fade it out
if ($(this).position().top < 0) {
$(this).stop().fadeTo(100, 0);
} else {
$(this).stop().fadeTo('fast', 1);
}
});
});
关于javascript - div 淡出内部 div 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40756198/