将项目隐藏在可见区域之外



我懒洋洋地在我的页面上加载项目(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";
}

最后一部分不起作用。我不明白为什么?

知道吗?

尝试更改

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 
}

我建议研究jquery-visible。查看演示。 当然,看看我的代码片段。也许这是正确的方式(对你来说(。无论如何,我希望它有所帮助。:)

$.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>

最新更新