我有以下功能,可以在图像进入视口后缩小图像。现在,它附加的事件侦听器与元素一样多。出于性能原因,我想将它们组合成一个所有元素的事件侦听器,但我不知道如何操作。这是我的代码:
断续器
<div class="image-wrapper">
<div class="image-container elem-1">
<div class="zoom-images">
<img class="zoom" src="test" alt="test">
</div>
</div>
<div class="image-container elem-2">
<div class="zoom-images">
<img class="zoom" src="test" alt="test">
</div>
</div>
<div class="image-container elem-3">
<div class="zoom-images">
<img class="zoom" src="test" alt="test">
</div>
</div>
</div>
JAVASCRIPT
$('.zoom').each(function() {
var el = $(this);
var inViewport = false;
var isZooming = false;
originY = 0;
window.addEventListener('scroll', throttle(zoomImage, 250), {passive: true});
function zoomImage() {
originY = $(window).scrollTop();
if (el.isInViewport()) {
if (!inViewport) {
inViewport = true;
}
} else {
if (inViewport) {
inViewport = false;
}
}
if (inViewport) {
if (!isZooming) {
window.requestAnimationFrame(function () {
el.addClass('is-zooming');
});
isZooming = true;
}
} else {
if (isZooming) {
window.requestAnimationFrame(function () {
el.removeClass('is-zooming');
});
isZooming = false;
}
}
};
$.fn.isInViewport = function() {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};
});
任何帮助将不胜感激!多谢!
慕仙森
喵喵时光机
相关分类