自动滑块滚动无法正常工作

时间:2018-10-18 09:53:43

标签: javascript html slider

您好!我尝试创建一个自动滚动滑块。这样很好,但是
当涉及到最后一张幻灯片时,它不会切换到第一张,而是停止。看我的html和JavaScript代码,我认为问题出在JS代码中。谢谢:

var inputs = $('input');
    setInterval(()=>{
        var next = inputs.filter(":checked").next('input');
        if (!next.length) next=inputs.first();
        next.prop('checked', true);
    }, 300);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slider">
  <input type="radio" name="slides" id="slide1" checked>
  <input type="radio" name="slides" id="slide2" >
  <input type="radio" name="slides" id="slide3" >
  <input type="radio" name="slides" id="slide4" >
  <input type="radio" name="slides" id="slide5" >
  <input type="radio" name="slides" id="slide6" >

  <div class="slider_helper">

      <div class="captions">
        <div class="c2">Prediction 2</div>
        <div class="c3">Prediction 3</div>
        <div class="c4">Prediction 4</div>
        <div class="c5">Prediction 5</div>
        <div class="c6">Prediction 6</div>
      </div>

      <div class="img img1"></div>
      <div class="img img2"></div>
      <div class="img img3"></div>
      <div class="img img4"></div>
      <div class="img img5"></div>
      <div class="img img6"></div>
  </div>

  <div class="side-controls">
    <label for="slide1"></label>
    <label for="slide2"></label>
    <label for="slide3"></label>
    <label for="slide4"></label>
    <label for="slide5"></label>
    <label for="slide6"></label>
  </div>

  <div class="controls">
    <label for="slide1"></label>
    <label for="slide2"></label>
    <label for="slide3"></label>
    <label for="slide4"></label>
    <label for="slide5"></label>
    <label for="slide6"></label>
  </div>

 </div>

2 个答案:

答案 0 :(得分:0)

您应该使用类似这样的内容:

<script type="text/javascript">
var inputs = $('input');
 var currentInput = inputs.first();
    setInterval(()=>{
        currentInput.prop('checked', true);
        if (currentInput.index()==inputs.last().index()) {
            currentInput = inputs.first();
        } else
            currentInput = inputs.filter(":checked").next('input');
    }, 300);
</script>

答案 1 :(得分:0)

将输入类型更改为单选input[type=radio]

var inputs = $('input[type=radio]');
    setInterval(()=>{
        var next = inputs.filter(":checked").next('input');
        if (!next.length) next=inputs.first();
        next.prop('checked', true);
    }, 500 );