【发布时间】:2021-12-14 03:19:45
【问题描述】:
有一个简单的 jQuery 滑块,但是当我从 Chrome 浏览器中退出时,一段时间后这个滑块会快速变化,以完成所有待处理的移动,当它处于不可见状态时。
现在我希望这个滑块在我从可见状态退出时必须暂停,并且当我回到这个状态时必须快速启动。
意味着我认为我需要设置一个 clearInterval(interval); 函数,我在这里阅读:jQuery when element becomes visible
但我不知道我应该在我的代码中更改什么。
请给我答案。
我的完整代码在这里:
$('#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>
【问题讨论】:
-
非常好的问题
标签: javascript html jquery css