定期间隔选择单选按钮不起作用

时间:2016-09-29 23:10:54

标签: javascript settimeout

我想定期自动更改单选按钮上的选择。我在每2000ms之后调用setTimeOut for for循环,但单选按钮的选择并没有随着我设置的间隔而改变。 这是我的代码: HTML:

<input type="radio" id="carousel1" name="carousel" checked="checked">
<input type="radio" id="carousel2" name="carousel">
<input type="radio" id="carousel3" name="carousel">

使用Javascript:

function autoSlideCarousel() {
  for (var n = 1; n <= 3; n++) {
    setTimeout(autoSlide(n), 2000); 
  }
}

function autoSlide(n) {
  console.log(n);
  document.getElementById("carousel"+n).checked = true;
}        

window.onload = autoSlideCarousel();

此处的JSFiddle链接更加清晰:https://jsfiddle.net/16zmfb12/1/

感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

In order to avoid running all 3 setTimeouts at once, use a global var for the counter instead of a for loop, and add the setTimeout to the end of the autoSlide() function.

var n = 1;

function autoSlide(n) {
  console.log(n);
  document.getElementById("carousel"+n).checked = true;
  if (n<3) {
    setTimeout(function() {autoSlide(n+1)},2000);
  }
}        

window.onload = function() {autoSlide(n)};

答案 1 :(得分:0)

使用setInterval代替,如下所示:

function autoSlideCarousel() {
    setInterval(function() {
      if(n == 3) 
         n = 1;
      else if(n == 2)
         n = 3;
      else
         n = 2;
      autoSlide(n)
    }, 2000); 
}

答案 2 :(得分:0)

我正在使用代码并最终得到以下解决方案: HTML:

<div id="carousel">CSS carousal</div>
<br>
<input type="radio" id="carousel1" name="carousel" checked="checked">
<input type="radio" id="carousel2" name="carousel">
<input type="radio" id="carousel3" name="carousel">

CSS:

#carousel {
  width: 200px;
  height: 200px;
  padding:20px;
  background: brown;
  color: #fff;
  text-align: center;
  font-size: 36px;
}

使用Javascript:

var n = 0;
window.ev = false;
function autoSlide() {
        document.getElementById("carousel").onmouseenter = function () {
            window.ev = true;
        };

        document.getElementById("carousel").onmouseleave = function () {
            window.ev = false;
            setTimeout(autoSlide, 2000);
        };

        if (window.ev == false) {
            n++;
            if (n === 4)
                n = 1;
            document.getElementById("carousel" + n).checked = true;
            setTimeout(autoSlide, 2000);
        }
    }
    autoSlide();

上面的解决方案为我提供了无限循环,其中每隔2000ms后选择单选按钮会发生变化,并且只要我的焦点位于Carousel div元素上就会停止。 https://jsfiddle.net/16zmfb12/13/