我懒洋洋地在页面上加载了这些项目(gif)。我的脚本工作正常。但是,当它们在可见区域之外时,我也想隐藏它们(display:none;
)。我的惰性加载脚本:
refresh_handler = function(e) {
var elements = document.querySelectorAll("*[realsrc]");
for (var i = 0; i < elements.length; i++) {
var boundingClientRect = elements[i].getBoundingClientRect();
if (elements[i].hasAttribute("realsrc") && boundingClientRect.top < window.innerHeight) {
elements[i].setAttribute("src", elements[i].getAttribute("realsrc"));
elements[i].removeAttribute("realsrc");
}
}
};
window.addEventListener('scroll', refresh_handler);
window.addEventListener('load', refresh_handler);
window.addEventListener('resize', refresh_handler);
我试图隐藏它们的方法是在for
循环中添加一个条件:
if (boundingClientRect.top > window.innerHeight) {
elements[i].getAttribute("src").style.display="none";
}
这最后一部分不起作用。我不明白为什么?
有什么主意吗?
答案 0 :(得分:0)
尝试更改
if (boundingClientRect.top > window.innerHeight) {
elements[i].getAttribute("src").style.display="none";
}
使用
if (boundingClientRect.top > window.innerHeight) {
elements[i].style.display="none"; // this will hide the element
}
答案 1 :(得分:0)
我建议您调查jquery-visible。请查看demo。 ,当然还要看一下我的代码段。也许这是正确的方法(适合您)。无论如何,我希望它会有所帮助。 :)
$.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() {
$('.color').each(function() {
var activeColor = $(this).attr('id');
if ($(this).isInViewport()) {
$('#fixed-' + activeColor).addClass(activeColor + '-active');
} else {
$('#fixed-' + activeColor).removeClass(activeColor + '-active');
}
});
});
html,
body {
height: 100%;
}
.fixed-red,
.fixed-green,
.fixed-blue {
width: 30px;
height: 30px;
position: fixed;
top: 10px;
left: 10px;
background: #333;
}
.fixed-green {
top: 50px;
}
.fixed-blue {
top: 90px;
}
.red-active {
background: #f00;
}
.green-active {
background: #0f0;
}
.blue-active {
background: #00f;
}
.color {
width: 100%;
height: 100%;
}
#red {
background: #900;
text-align: center;
font-size:3rem;
font-weight: bold;
}
#green {
background: #090;
text-align: center;
font-size:3rem;
font-weight: bold;
color: yellow;
}
#blue {
background: #009;
text-align: center;
font-size:3rem;
font-weight: bold;
color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fixed-red" class="fixed-red red-active"></div>
<div id="fixed-green" class="fixed-green"></div>
<div id="fixed-blue" class="fixed-blue"></div>
<div id="red" class="color">Viewport 1</div>
<div id="green" class="color">Viewport 2</div>
<div id="blue" class="color">Viewport 3</div>