我有一个 CSS 关键帧动画,当元素滚动到视图中时,通过将类添加到我只想在它们滚动到视图中时设置动画的元素。它在 Firefox 中按预期工作,但由于某种原因它在 Chrome 中不起作用。开发人员工具表明,即使元素在视口中,也没有将start类添加到其中。任何想法为什么这在 chrome 中不起作用?
查询:
function isElementInViewport(elem) {
var $elem = $(elem);
// Get the scroll position of the page.
var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html');
var viewportTop = $(scrollElem).scrollTop();
var viewportBottom = viewportTop + $(window).height();
// Get the position of the element on the page.
var elemTop = Math.round($elem.offset().top);
var elemBottom = elemTop + $elem.height();
return ((elemTop < viewportBottom) && (elemBottom > viewportTop));
}
// Check if it's time to start the animation.
function checkAnimation() {
var $elem = $('.parent-content-block .slide-in');
// If the animation has already been started
if ($elem.hasClass('start')) return;
if (isElementInViewport($elem)) {
// Start the animation
$elem.addClass('start');
}
}
// Capture scroll events
$(window).scroll(function () {
checkAnimation();
});
document.addEventListener("DOMContentLoaded", function() {
var elements = document.querySelectorAll(".slide-in");
// Intersection observer
var observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.intersectionRatio > 0) {
entry.target.classList.add("start");
}
});
});
elements.forEach((el) => {
observer.observe(el);
});
});
<div>
<img class="slide-in slide1" src="img.png">
<div style="height: 200vh">
scroll down
</diV>
<img class="slide-in slide1" src="img.png">
<img class="slide-in slide2" src="img.png">
<!-- other html... -->
</div>
达令说
相关分类