有這個代碼,它檢查類是否在視圖中,如果它是添加一個類,但出於一些外在原因它確實工作。我正在嘗試添加類框 - 活動只有在視圖中的div。Jquery添加一個類,當元素在視圖中
我已經有一段時間了,你們可以告訴我代碼有什麼問題嗎?和一個可能的修復或我可以修復它。
codepen:http://codepen.io/salman15/pen/rLRZrJ
jQuery的
$(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);
};
你爲什麼要加入你的完整的項目? :P你可以只添加相關的代碼 –
有時我得到的HTML請求:D – Salman
你重複點擊功能一遍又一遍...... jquery是一種混亂。你只需要一個點擊功能..然後if語句。你的方式,我很驚訝的事情發生,如你所料。 – Scott