我知道之前有人问过这个问题,但这些解决方案对我不起作用。这可能与使用的图像有关。
这是我的 html:
<div id="tour">
<section class="first js-background"> // this section is repeated 5 more times
<div class="background js-first"></div>//image located in here 300 px height
<div class="copy">
<h6>Line one</h6>
<h1 class="space large">Line two</h1>
<h6>Line three</h6>
</div>
</section>
</div>
检查是否可见的 javascript:
$('.js-background').each(function(x, item) {
var $current = $(item),
$window = $(window),
elemTop = $current.offset().top,
elemBottom = elemTop + $current.height(),
docViewTop = $(window).scrollTop(),
docViewBottom = docViewTop + $(window).height(),
if ((elemBottom >= docViewTop) && (elemTop <= docViewBottom)
&& (elemBottom <= docViewBottom) && (elemTop >= docViewTop) ) {
//do code here if true
}
}
我也试过这个plugin
代码:
if ($current.visible()) {
//if visible do something
}
对于这两种类型的代码,当我在浏览器窗口中仅显示第一部分的情况下触发函数时。 if 语句返回 true 6 次。
图片是背景而不是 img 标签
CSS:
#tour .first .background{
background: url('/Content/images/1.jpg') center center no-repeat;
background-size: 100%;
height: 350px;
}
最佳答案
您可以使用 jQuery 的 :visible
检查。只需选择 if($('.first').is(':visible')){ 这样的元素
//做一点事
}
关于javascript - 检查屏幕上是否存在 html 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18522489/