Bootstrap Carousel为每张幻灯片提供不同的URL

时间:2016-07-09 14:05:44

标签: javascript jquery css twitter-bootstrap

我的引导程序轮播位于此处:https://testdomain.org/about.html#slide1 https://testdomain.org/about.html#slide2 https://testdomain.org/about.html#slide3 ,当幻灯片更改时,地址栏中的URL保持不变。当幻灯片更改为以下内容时,我希望URL自动更改:

<div id="myCarousel" class="carousel slide" data-ride="carousel">
  <!-- Wrapper for slides -->
  <div class="carousel-inner" role="listbox">
    <div class="item active">
      <img src="img_chania.jpg" alt="Chania">
      <div class="">
        <h3>Chania</h3>
        <p>The atmosphere in Chania has a touch of Florence and Venice.</p>
      </div>
    </div>

    <div class="item">
      <img src="img_chania2.jpg" alt="Chania">
      <div class="">
        <h3>Chania</h3>
        <p>The atmosphere in Chania has a touch of Florence and Venice.</p>
      </div>
    </div>

    <div class="item">
      <img src="img_flower.jpg" alt="Flower">
      <div class="">
        <h3>Flowers</h3>
        <p>Beatiful flowers in Kolymbari, Crete.</p>
      </div>
    </div>

    <div class="item">
      <img src="img_flower2.jpg" alt="Flower">
      <div class="">
        <h3>Flowers</h3>
        <p>Beatiful flowers in Kolymbari, Crete.</p>
      </div>
    </div>
  </div>

  <!-- Left and right controls -->
  <a class="left carousel-control" href="#myCarousel" 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="#myCarousel" role="button" data-slide="next">
    <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
    <span class="sr-only">Next</span>
  </a>
</div>

我们如何实现这一目标?为方便起见,我创建了此JSFiddle Demo。我不知道如何为此写JS :(

它是标准的引导程序HTML:

char c = (char)88;

DEMO地址栏中URL的屏幕截图应如下所示 enter image description here

2 个答案:

答案 0 :(得分:0)

使用轮播事件确定幻灯片转换何时发生以及哪个幻灯片已激活。然后使用幻灯片URL更新地址栏和浏览器历史记录。两者的说明见以下链接:

http://getbootstrap.com/javascript/#carousel-events

Updating address bar with new URL without hash or reloading the page

答案 1 :(得分:0)

尝试添加以下javascript,修改适用的参考。您还需要向<div class="carousel-inner" role="listbox">添加ID。我在下面做了以下工作 - <div class="carousel-inner" id="listbox" role="listbox">

childsList = Array.prototype.slice.call( document.getElementById('listbox').children );

$("#myCarousel").on('slide.bs.carousel', function (event) {
  window.location.hash = "slide" + (childsList.indexOf(event.relatedTarget) + 1);
}

这会选择幻灯片更改的事件,选取幻灯片的索引并将URL中的“#”设置为“#slide [幻灯片的索引+ 1]”。我希望这会有所帮助。

这是一个小提琴做同样的事情,但输出到一个而不是URL。 https://jsfiddle.net/JokerDan/22botkvm/