twitter bootstrap carousel直接链接到特定幻灯片

use*_*208 10 javascript jquery twitter-bootstrap

我在我的网站上使用twitter bootstrap carousel来显示一组图像.我想知道是否可以允许链接链接到轮播中的特定幻灯片.因此,在10个幻灯片中,用户可以单击链接直接从href链接说出幻灯片5.

这是可能的自助旋转木马还是我咆哮错误的树?

编辑

嗨,所以我在document.ready函数下添加了以下javascript.

但是,输入网址并www.example.com/models.php/5不会做任何事情.
难道我做错了什么?

var url = window.location.href;
var slide = url.substring(url.lastIndexOf('/')+1); // 4
goToSlide(slide);

function goToSlide(number) {
    $("#MyCarousel").carousel(number);
}
Run Code Online (Sandbox Code Playgroud)

meh*_*kin 18

无JavaScript的方式

您可以使用此data-slide-to属性,它接受基于0的索引表示幻灯片编号.

使用数据属性可以轻松控制轮播的位置.data-slide接受关键字prevnext,它相对于当前位置改变幻灯片位置.或者,用于data-slide-to将原始幻灯片索引传递给轮播data-slide-to="2",轮播将幻灯片位置移动到以...开头的特定索引0.

只需在锚点中添加一个属性,然后就可以了.

<a href="#" data-slide-to="5">Go to slide #5</a>
Run Code Online (Sandbox Code Playgroud)

感谢Cawas对这个答案的评论以及Jonas对这个问题的回答.


老派的JavaScript方式

您需要使用该.carousel(number)功能.

.carousel(数字)

将轮播循环到特定帧(基于0,类似于数组).

查看bootstrap文档.

更具体;

创建一个要调用的javascript函数,它应该如下所示:

function goToSlide(number) {
   $("#carousel").carousel(number);
}
Run Code Online (Sandbox Code Playgroud)

然后,只需在链接上添加onClick事件即可.

<a href="#" onClick="javascript:goToSlide(5);">Go to slide #5</a>
Run Code Online (Sandbox Code Playgroud)

从URL获取幻灯片信息

源链接是 www.example.com/models.php/4

您可以检查网址document.ready,如果网址末尾有一些数据,您只需调用goToSlide函数即可.

var url = window.location.href;
var slide = url.substring(url.lastIndexOf('/')+1); // 4

// Remove the trailing slash if necessary
if( slide.indexOf("/") > -1 ) { 
    var slideRmvSlash = slide.replace('/','');
    slide = parseInt(slideRmvSlash);
}
goToSlide(slide);
Run Code Online (Sandbox Code Playgroud)

  • +1但是一个小问题:更好地使用不引人注意的标记,如`<a href="#" data-slide="5"> ...... </a>`,然后在js中编写处理程序,如`$("[data -slide]").click(function(e){e.preventDefault(); ...});`. (3认同)