停止并恢复JavaScript上的运行功能

时间:2019-05-25 16:33:04

标签: javascript

嗨,

这是我的代码:

var myIndex = 0;
carousel();

function carousel() {
  var i;
  var x = document.getElementsByClassName("areaslide");
  var y = document.getElementsByClassName("arealink");
  for (i = 0; i < x.length; i++) {
    x[i].style.opacity = "0";
    y[i].style.backgroundColor = "";  
  }
  myIndex++;
  if (myIndex > x.length) {myIndex = 1}    
  x[myIndex-1].style.opacity = "100";
  y[myIndex-1].style.backgroundColor = "#ad9463";  
  setTimeout(carousel, 3000); // Change image every 2 seconds

}

此功能在页面加载时开始执行,但是当鼠标悬停在此元素上时,我需要它停止运行:

<a href="" class="arealink" onmouseover="stopfunction()" onmouseout="resumefunction()">some link</a>

,该功能应在onmouseout上恢复。我该怎么办?

谢谢。

3 个答案:

答案 0 :(得分:2)

做完一些研究后,我建议为此使用interval

它会为您重复一些操作,因此您不必递归启动timeout。 然后,您可以使用interval清除mouseenter上的window.clearInterval,然后在mouseleave上设置一个新间隔,如下所示:

var myInterval;

function move() {
  document.getElementById('carousel').classList.toggle('moved');
}

function start() {
  myInterval = window.setInterval(move, 2000);
}

function stop() {
  window.clearInterval(myInterval);
}

start();
#wrapper {
  width: 200px;
  height: 200px;
  overflow: hidden;
}

#carousel {
  width: 200%;
  height: 100%;
  margin-left: 0;
  transition: margin-left 0.2s;
  background: linear-gradient(to right, #646464 50%, #ccc 50%);
}

#carousel.moved {
  margin-left: -100%;
}
<div id="wrapper">
  <div id="carousel" onmouseenter="stop()" onmouseleave="start()"></div>
</div>

答案 1 :(得分:2)

您的stopFunctionresumeFunction可以为是否继续骑行设置一个标记。然后,您的轮播功能可以检查是否应该循环。

var doCycle=true;
function stopFunction(){
    doCycle=false;
}

function resumeFunction(){
    doCycle=true;
}

function carousel() {
  if(doCycle){//if you are not cycling, do not change the picture. But it still checks again in 3 seconds.
    var i;
    var x = document.getElementsByClassName("areaslide");
    var y = document.getElementsByClassName("arealink");
    for (i = 0; i < x.length; i++) {
      x[i].style.opacity = "0";
      y[i].style.backgroundColor = "";  
    }
    myIndex++;
    if (myIndex > x.length) {myIndex = 1}    
    x[myIndex-1].style.opacity = "100";
    y[myIndex-1].style.backgroundColor = "#ad9463";  
  }
  setTimeout(carousel, 3000); // Change image every 3 seconds

}

答案 2 :(得分:0)

您可以使用return语句退出该函数,并且只有在设置了条件的情况下才执行该函数的一部分。

function carousel() {
  var i;
  var x = document.getElementsByClassName("areaslide");
  var y = document.getElementsByClassName("arealink"); 

  if (nostop) {
    for (i = 0; i < x.length; i++) {
        x[i].style.opacity = "0";
        y[i].style.backgroundColor = "";  
      }
      myIndex++;
      if (myIndex > x.length) {myIndex = 1}    
      x[myIndex-1].style.opacity = "100";
      y[myIndex-1].style.backgroundColor = "#ad9463";  
      setTimeout(carousel, 3000); // Change image every 2 seconds
      }
    else {
        return null
}

}