我想知道如何将jQuery中的代码转换为纯Javascript
$('.revealedBox').each(function() {
if ($(window).scrollTop() + $(window).height() > $(this).offset().top + $(this).outerHeight()) {
$(this).addClass('revealedBox-in');
}
});
$(window).scroll(function() {
$('.revealedBox').each(function() {
if ($(window).scrollTop() + $(window).height() > $(this).offset().top) {
$(this).addClass('revealedBox-in');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
该代码用于当元素在屏幕上可见时运行动画。但是.revealedBox类有几个元素
我如何在纯Javascript中做同样的事情呢?
发布于 2020-03-10 15:22:07
你不需要滚动事件来做这件事,你可以用Intersection Observer API (IO)来做。创建IO是为了解决类似您的问题,当元素在视口中变得可见或彼此相交(或彼此相交)时做出反应。
首先,您需要定义IO的选项:
let options = {
rootMargin: '0px',
threshold: 1.0
}
在定义选项之后,您可以说出您想要观察的元素:
const elements = document.querySelectorAll('.revealedBox');
作为最后一步,您必须定义元素进入视图后会发生什么,并将其绑定到您定义的元素:
const intersectionObserver = new IntersectionObserver((entries, observer) => {
entries.forEach((entry) => {
// when element's is in viewport,
// do something with it!
if (entry.intersectionRatio > 0) {
animate(entry.target); // example: call an "animate" function if you need to animate the element that's getting into view.
// Just do whatever you want with the element here
console.log(entry.target);
// remove observer after animation (if it is no longer needed).
// remove this line if you want to continue observing this element.
observer.unobserve(entry.target);
}
});
});
elements.forEach((element) => intersectionObserver.observe(element));
如果你需要支持比使用这个(官方) polyfill from w3c更老的浏览器,它会重新创建带有侦听滚动事件的交叉点观察器。所以在老版本的浏览器上它仍然会更慢,你在这里对此无能为力。但在较新的版本中,性能会有所提高。
这是一个完整的how to animate an element示例,只要您将它滚动到视图中。(向下滚动查看它的实际效果)
https://stackoverflow.com/questions/60610756
复制相似问题