有这段代码可以检查该类是否在 View 中,如果在 View 中,它会添加一个类,但出于某些明显的原因,它确实有效。我试图仅在 div 可见时才添加 box-active 类。
我已经研究了一段时间了,你们能告诉我代码有什么问题吗?以及可能的修复方法或我该如何修复它。
代码笔:http://codepen.io/salman15/pen/rLRZrJ
查询
$(document).ready(function() {
$('#next').click(function() {
if ($('.in1,.in2,.in3').next('.t1,.t2,.t3').length) {
$('.t1').animate({
left: '-1000px'
})
$('.in1').removeClass('in1')
.next('.t1')
.addClass('in1');
$('.t2').animate({
right: '-1000px'
})
$('.in2').removeClass('in2')
.next('.t2')
.addClass('in2');
$('.t3').animate({
bottom: '-1000px'
})
$('.in3').removeClass('in3')
.next('.t3')
.addClass('in3');
}
});
$('#prev').click(function() {
if ($('.in1,.in2,.in3').prev('.t1,.t2,.t3').length) {
$('.t1').animate({
left: '-1000px'
})
$('.in1').removeClass('in1')
.prev('.t1')
.addClass('in1');
$('.t2').animate({
right: '-1000px'
})
$('.in2').removeClass('in2')
.prev('.t2')
.addClass('in2');
$('.t3').animate({
bottom: '-1000px'
})
$('.in3').removeClass('in3')
.prev('.t3')
.addClass('in3');
}
});
});
$.fn.isVisible = function() {
// Am I visible?
// Height and Width are not explicitly necessary in visibility detection, the bottom, right, top and left are the
// essential checks. If an image is 0x0, it is technically not visible, so it should not be marked as such.
// That is why either width or height have to be > 0.
var rect = this[0].getBoundingClientRect();
return (
(rect.height > 0 || rect.width > 0) &&
rect.bottom >= 0 &&
rect.right >= 0 &&
rect.top <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.left <= (window.innerWidth || document.documentElement.clientWidth)
);
};
if ($('.box').isVisible()) {
setTimeout(function(){
$('.box').removeClass('box-active')}, 4000);
} else{
setTimeout(function(){
$('.box').addClass('box-active')}, 4000);
};
最佳答案
为什么不使用 .animate 中的结束事件? 在您的一个动画完成后,您可以轻松地向任何元素添加一个类。
引用:http://api.jquery.com/animate/
例子:
var clicked = 1;
$("button").click(function(){
/* just for the demo */
if(clicked==4){
clicked = 2;
$(".inner").css("margin-left","0px");
}
else clicked++;
/* - */
if($(".box-active").length == 1) $(".box-active").removeClass("box-active");
$(".inner").animate({marginLeft :"-=250px"},"slow",function(){
//WHEN ANIMATION IS COMPLETE
// Add the box-active class
$("div.a"+clicked+"").addClass("box-active");
});
});
.outer{
width:250px;
height:100px;
overflow:hidden;
}
.inner{
width:1000px;
height:100px;
margin-left:0px;
}
.inner > div{
width:250px;
height:100px;
float:left;
}
.a1{
background:blue;
}
.a2{
background:red;
}
.a3{
background:green;
}
.a4{
background:grey;
}
.box-active{
background:cyan !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Next</button>
<div class="outer">
<div class="inner">
<div class="a1 box-active"></div>
<div class="a2"></div>
<div class="a3"></div>
<div class="a4"></div>
</div>
</div>
关于Jquery 在元素处于 View 中时添加一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39039042/