如何更新单选按钮的状态以匹配轮播状态?

时间:2016-04-18 10:38:13

标签: javascript html twitter-bootstrap

我使用单选按钮作为我的旋转木马的分页,效果很好。如果我使用轮播按钮而不是单选按钮更改幻灯片,则单选按钮的状态不会更改,因此所选按钮与所选幻灯片不匹配。我该如何解决这个问题?

Here is my template

HTML:

<div class="container">
    <div id="carousel" class="carousel slide" data-interval="false" data-ride="carousel">
      <div class="carousel-inner" role="listbox">
        <div class="item active">
          <img class="img-responsive center-block" src="http://www.w3schools.com/bootstrap/img_chania.jpg">
        </div>
        <div class="item">
          <img class="img-responsive center-block" src="http://www.w3schools.com/bootstrap/img_chania2.jpg">
        </div>
        <div class="item">
          <img class="img-responsive center-block" src="http://www.w3schools.com/bootstrap/img_flower.jpg">
        </div>
        <div class="item">
          <img class="img-responsive center-block" src="http://www.w3schools.com/bootstrap/img_flower2.jpg">
        </div>
      </div>
      <a class="left carousel-control" href="#carousel" role="button" data-slide="prev">
        <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span>
        <span class="sr-only">Previous</span>
      </a>
      <a class="right carousel-control" href="#carousel" role="button" data-slide="next">
        <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
        <span class="sr-only">Next</span>
      </a>
    </div>
  </div>
  <br>
  <center>
    <div class="btn-group" data-toggle="buttons">
      <label class="btn btn-primary active s1"><input type="radio" name="options" autocomplete="off" checked>1</label>
      <label class="btn btn-primary s2"><input type="radio" name="options" autocomplete="off">2</label>
      <label class="btn btn-primary s3"><input type="radio" name="options" autocomplete="off">3</label>
      <label class="btn btn-primary s4"><input type="radio" name="options" autocomplete="off">4</label>
    </div>
  </center>

JS:

$(function () {
    $(".s1").click(function () {$("#carousel").carousel(0);});
    $(".s2").click(function () {$("#carousel").carousel(1);});
    $(".s3").click(function () {$("#carousel").carousel(2);});
    $(".s4").click(function () {$("#carousel").carousel(3);});
});

2 个答案:

答案 0 :(得分:2)

如果您想保持原样,可以添加

$('#carousel').on('slide.bs.carousel', function (e) {
    var idx = $(e.relatedTarget).index() + 1;
    $('.s'+idx).button('toggle');
});

但是

$(function () {
    $(".s1").click(function () {$("#carousel").carousel(0);});
    $(".s2").click(function () {$("#carousel").carousel(1);});
    $(".s3").click(function () {$("#carousel").carousel(2);});
    $(".s4").click(function () {$("#carousel").carousel(3);});
});

不是那么好主意。我建议改变它,使它像this

答案 1 :(得分:0)

我已经解决了这个问题)

这是一个固定的JS:

$(document).ready(function() {
  $('#carousel').on('slide.bs.carousel', function(e) {
    var idx = $(e.relatedTarget).index();
    $('[data-slide-to=' + idx + ']').button('toggle');
  });
});

Here is the working Template