我正在尝试制作一个简单的两个图像 slider ,可以自动上下滑动。当用户将鼠标悬停在其中时,它应该停止,如果他/她将鼠标悬停在其中,它会继续正常运行。我尝试使用 set 和 clearInterval 但 slider 不会在悬停时暂停。我应该如何编写代码才能使其工作?
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();
最佳答案
这里有两个主要问题:
clearInterval
不会停止jquery
的动画,它只会停止您的setInterval
调用,以便不再添加更多动画在队列中。您已经通过管道传送且仍待处理的每个动画仍将运行。全部完成后就会停止。您没有为
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>
关于javascript - 设置和清除间隔 slider jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33064886/