javascript - 当它处于不可见状态时如何停止更改此 jQuery 简单 slider 中的幻灯片

标签 javascript html jquery css

有一个简单的 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>

最佳答案

我认为最好使用 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()
})

关于javascript - 当它处于不可见状态时如何停止更改此 jQuery 简单 slider 中的幻灯片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69762270/

相关文章:

javascript - 获取选择列表中的单选按钮值

javascript - Bootstrap Accordion - 设置为特定高度

javascript - 如何检查此示例中的复选框是否已选中(javascript/jQuery。)

javascript - 在 .content div 之间导航

javascript - 大量日期输入项的 Bootstrap Datepicker 性能问题

javascript - Chrome : Recover document focus after jquery fadeOut

javascript - Angular ES6 Controller 范围

javascript - 从 URL/地址栏调用 Javascript 函数

javascript - 如何让输入字段在提交后添加文本

php - 如何隐藏 native php 中我网站上链接的其他网站的链接