使用不同的主题标签URL创建Bootstrap Carousel幻灯片

时间:2016-07-07 03:03:28

标签: javascript jquery html twitter-bootstrap

我试图从另一个页面链接到引导程序轮播中的不同幻灯片但没有结果。

这样的事情:

<a href="services#slide2">Link to Slide2</a>

仅供参考,这是标准的bootstrap轮播:

<div class="container">
  <div id="myCarousel" class="carousel slide" data-ride="carousel">
    <ol class="carousel-indicators">
      <li data-target="#myCarousel" data-slide-to="0" class="active"></li>
      <li data-target="#myCarousel" data-slide-to="1"></li>
    </ol>

    <!-- Wrapper for slides -->
    <div class="carousel-inner" role="listbox">
      <div class="item active">
        <img src="img_chania.jpg" alt="Chania" width="460" height="345">
      </div>

      <div class="item">
        <img src="img_chania2.jpg" alt="Chania" width="460" height="345">
      </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>
</div>

我试过这个,但只有当它在同一页面时它才有效:

<a href="#" onClick="javascript:goToSlide(3);">Go to slide #4</a>
<script>
function goToSlide(number) {
   $("#myCarousel").carousel(number);
}
</script>

即使是包含不同幻灯片的网址也可以。像

这样的东西
mydomain.com/services#slide1
mydomain.com/services#slide2
mydomain.com/services#slide3

1 个答案:

答案 0 :(得分:0)

您需要在页面加载时和转盘准备好后调用相同的函数。从URL哈希中获取数字并将其传递给函数:

$(document).ready(function() {
    var number = window.location.hash.replace(/^\D+/g, '');//Get the number
    goToSlide(number); //pass it on
});

您还需要绑定一个hashchange事件:

$(window).on('hashchange', function() {
    var number = window.location.hash.replace(/^\D+/g, '');
    goToSlide(number);
});

从锚标记中删除onclick