有一个简单的jQuery滑块,但是当我离开Chrome浏览器,过了一段时间后,这个滑块变化快速滑动,以完成所有未决的移动,当它处于不可见的状态。
现在我想这个滑块必须暂停当我离开可见状态,必须快速启动当我回到这个
意味着我认为我需要设置一个clearInterval(interval);
函数,我在这里阅读:jQuery当元素变得可见
但是我不知道我应该在我的代码中修改什么。
请告诉我答案。
我的全部代码在这里:
$('#slider').each(function() {
let currentPosition = 0; //Set the starting position of the photo
let photo = $('.photo');
let photoNums = photo.length; //Number of photos
let speed = 400;
let timeout = 2000; // How long does each photo stay
$('.photo').eq(0).show();
function move(){
// Change the number of sheets displayed through the concept of remainder
let nextPhoto = (currentPosition + 1) % photoNums;
photo.eq(currentPosition).fadeOut(speed);
photo.eq(nextPhoto).fadeIn(speed);
currentPosition = nextPhoto;
}
setInterval(move,timeout);
})
#slider {
width: 600px;
height: 300px;
position: relative;
margin: auto;
}
img {
width: 100%;
}
.photo {
position: absolute;
display: none;
}
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>
<div id="slider">
<div class="photo"><img src="https://source.unsplash.com/random/1200x600?sig=1" alt=""></div>
<div class="photo"><img src="https://source.unsplash.com/random/1200x600?sig=2" alt=""></div>
<div class="photo"><img src="https://source.unsplash.com/random/1200x600?sig=3" alt=""></div>
<div class="photo"><img src="https://source.unsplash.com/random/1200x600?sig=4" alt=""></div>
</div>
我认为最好使用setTimeOut而不是setInterval。并放慢每张照片的移动速度。
$('#slider').each(function() {
let currentPosition = 0; //Set the starting position of the photo
let photo = $('.photo');
let photoNums = photo.length; //Number of photos
let speed = 800;
let timeout = 2000; // How long does each photo stay
$('.photo').eq(0).show();
function move(){
// Change the number of sheets displayed through the concept of remainder
let nextPhoto = (currentPosition + 1) % photoNums;
photo.eq(currentPosition).fadeOut(speed);
photo.eq(nextPhoto).fadeIn(speed);
currentPosition = nextPhoto;
setTimeout(move,speed)
}
move()
})