我正在尝试添加显示图像的类。 JSFIDDLE
这里有两个图片。我正在尝试在屏幕上显示任何图像时添加类。现在只添加第一个图像。 我试图检查closest(),但没有得到任何值
function isScrolledIntoView(elem) {
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
return ((elemTop <= docViewBottom) && (elemTop >= docViewTop));
}
$(window).scroll(function(){
if (isScrolledIntoView('.box')) {
console.log($(this).find('img').html());
$('img').addClass('animated flip').css('background', 'red');
//added background red so you can see it has triggered
}
else {
$('img').removeClass('animated flip');
}
});
.col-md-12 {
height: 1500px;
padding-top: 1000px;
}
.box{
position:relative;
}
.animated {
opacity: 1;
visibility: visible;
transition: opacity 1s 0s, visibility 1s 0s;
z-index: 2;
position: fixed;
top: 0;
left: 0;
}
.rad-slideshow-item {
/* position: relative; */
}
.rad-slideshow-item .rad-asset-wrapper {
display: block;
padding: 0;
position: absolute;
top: 0;
left: 0;
overflow: hidden;
z-index: 3;
}
.animated .rad-slideshow-item.active-adjacent div.rad-asset-wrapper {
background: #000;
opacity: 0;
visibility: hidden;
position: fixed;
top: 0;
left: 0;
transition: opacity 0s 0s, visibility 0s 0s;
z-index: 1;
display: none;
}
.animated .rad-slideshow-item.active-adjacent div.rad-asset-wrapper {
display: block;
transform: translate3d(0, 0, 0);
transition: opacity 0s 1s, visibility 0s 1s;
}
.rad-spinner {
position: absolute;
top: 50%;
left: 50%;
z-index: 2;
transform: translate3d(-50%, -50%, 0);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="col-md-12 ">
<div class="box">
<img src="https://dummyimage.com/800x800" class="icon"/>
<div class="rad-slideshow-item active-adjacent">
<div class="rad-asset-wrapper">
<h1>WEB<br/>DESIGN</h1>
</div>
</div>
</div>
<div class="box">
<img src="https://dummyimage.com/800x800" class="icon"/>
<div class="rad-slideshow-item active-adjacent">
<div class="rad-asset-wrapper">
<h1>WEB<br/>DESIGN</h1>
</div>
</div>
</div>
</div>
答案 0 :(得分:0)
您可以使用ScrollMonitor
var el = $(".box");
var watcher = scrollMonitor.create( el );
watcher.enterViewport(function() {
console.log( 'I have entered the viewport' );
el.addClass('animated flip').css('background', 'red');
});
watcher.exitViewport(function() {
console.log( 'I have left the viewport' );
el.removeClass('animated flip').css('background', 'none');
});
答案 1 :(得分:0)
用于检查元素的功能是否存在于视口中。 elementInViewport
已从此SO_Answer中提取。寻求更多了解。
function elementInViewport(el) {
var top = el.offsetTop;
var left = el.offsetLeft;
var width = el.offsetWidth;
var height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top < (window.pageYOffset + window.innerHeight) &&
left < (window.pageXOffset + window.innerWidth) &&
(top + height) > window.pageYOffset &&
(left + width) > window.pageXOffset
);
}
jsFiddle演示了console.log
元素在视口中的状态。