【问题标题】:Set and Clear interval slider jQuery设置和清除间隔滑块jQuery
【发布时间】:2015-10-11 12:21:30
【问题描述】:

我正在尝试制作一个简单的两个图像滑块,可以自动上下滑动。当用户悬停在其中时,它应该停止,如果他/她悬停在其中,它会继续正常运行。我尝试使用 set 和 clearInterval 但滑块不会在悬停时暂停。我应该如何编写代码以使其工作?

var $Slides = $("#EServices"); //Or var $Slides = $("#Serv-Slides");
var interval;
function StartSlider() {
interval = setInterval(function () {
        $("#Serv-Slides").animate({ "marginTop": "0px" }, 200).delay(2000);
        $("#Serv-Slides").animate({ "marginTop": "-150px" }, 200).delay(2000);
    });
}

function StopSlider() {
    clearInterval(interval);
}

$Slides.on('mouseenter', StopSlider).on('mouseleave', StartSlider);
StartSlider();

【问题讨论】:

  • 什么是$Slides?控制台中抛出的任何错误?显示所有相关代码
  • var $Slides = $("#EServices");
  • interval的超时时间在哪里?

标签: javascript jquery html


【解决方案1】:

这里有两个主要问题:

  1. clearInterval 不会停止 jquery 的动画,它只会停止您的 setInterval 调用,因此不会在队列中添加更多动画。您已通过管道传输且仍处于挂起状态的每个动画仍将运行。全部完成后就会停止。

  2. 您没有为您的setInterval 提供任何给定时间。因此,提供的函数将尽可能快地重复调用您的浏览器。这是一个可怕的错误,因为您最终会在队列中看到大量待处理的动画。您传递新动画的速度比实际消耗的快得多。

这应该可行:

var interval;
function startSlider() {
  function animate(){
    $("#Serv-Slides").animate({ "marginTop": "0px" }, 200).delay(2000)
                     .animate({ "marginTop": "-150px" }, 200); //.delay(2000);
    // Last delay is useless, it is managed by the setInterval.
  }
  // Start the first animation right now.
  animate();
  // Set an interval that matches the animations and the delays duration.
  interval = setInterval(animate, 200 + 2000 + 200 + 2000);
}

function stopSlider() {
  // Avoid any further animation to be added.
  clearInterval(interval);
  // Stop the currently running animations.
  $("#Serv-Slides").stop(true);
}

$("#Slides").on('mouseenter', stopSlider).on('mouseleave', startSlider);
startSlider();
#Slides{
    background-color:yellow;
    padding-top: 150px;
    height: 20px;
}
#Serv-Slides{
    background-color: red;
    height: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Slides">
   <div id="Serv-Slides"></div>
</div>

您也可以考虑将css animations@keyframes 一起使用。使用 :hover 伪类,您甚至不需要任何 JavaScript。这可能会更高效,我个人觉得它更优雅、更容易、更灵活。这是一个示例(您可能需要添加 css 前缀以支持旧浏览器):

#Slides{
    background-color:yellow;
    padding-top: 150px;
    height: 20px;
}
#Serv-Slides{
    background-color: red;
    height: 20px;
    animation-duration: 4s;
    animation-name: up-and-down;
    animation-iteration-count: infinite;
}
#Slides:hover #Serv-Slides{
    animation-play-state: paused;
}
@keyframes up-and-down {
    0%  { margin-top: 0px; }
    45% { margin-top: 0px; }
    50% { margin-top: -150px; }
    95% { margin-top: -150px; }
}
<div id="Slides">
   <div id="Serv-Slides"></div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-27
    • 2020-09-28
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多