我的任务是将 jQuery 函数转换为纯 JavaScript。该函数用于检查元素是否在视口内。如果它在视口内,则使用 data-bglazy 属性并使用该属性的值向该元素添加背景图像样式。需要转换的函数是:
$.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;
};
$(window).on('resize scroll', function() {
$('.bgLazy').each(function() {
if ($(this).isInViewport()) {
var lazyImg = $(this).attr('data-bglazy');
$(this).css('background-image', 'url(' + lazyImg + ')');
}
});
});
目前我在尝试将上述函数转换为 JavaScript 时所拥有的:
function isInViewport(el){
var elementTop = el.offsetTop;
var elementBottom = elementTop + el.offsetHeight;
var viewportTop = window.scrollTop;
var viewportBottom = viewportTop + window.offsetHeight;
return elementBottom > viewportTop && elementTop < viewportBottom;
};
var bgElements = document.querySelectorAll('.bgLazy');
bgElements.forEach(bgElementLoop);
function bgElementLoop(item, index) {
if(item.isInViewport()){
var lazyImg = item.getAttribute('data-bglazy');
item.style.backgroundImage = 'url(' + lazyImg + ')';
}
}
window.addEventListener("resize, scroll", bgElementLoop);
我试图弄清楚在尝试将 jQuery 函数转换为 JavaScript 时我搞砸了哪一部分
编辑:
在阅读了一些评论后,我对视图进行了更改。isInViewport 函数没有改变,但我所做的改变如下:
var bgElements = Array.prototype.slice.call(document.querySelectorAll('.bgLazy'));
bgElements.forEach(bgElementLoop);
function bgElementLoop(item, index) {
if(item.isInViewport(item)){
var lazyImg = item.getAttribute('data-bglazy');
item.style.backgroundImage = 'url(' + lazyImg + ')';
}
}
window.addEventListener("resize", bgElementLoop);
window.addEventListener("scroll", bgElementLoop);
相关分类