【发布时间】:2013-12-11 14:56:58
【问题描述】:
下面的代码根据轮播幻灯片更新散列 - 我希望根据散列更新幻灯片。这个问题很好地解释了它。
有一个很好的方法来更新 window.location.hash onslide
var url = document.location.toString();
if (url.match('#')) {
// Clear active item
$('#my-carousel-id .carousel-inner .item.active').removeClass('active');
// Activate item number #hash
$('.carousel-inner div:nth-child(' + url.split('#')[1] + ')').addClass('active');
}
$('#my-carousel-id').bind('slid', function (e) {
// Update location based on slide (index is 0-based)
window.location.hash = "#"+ parseInt($('#my-carousel-id .carousel-inner .item.active').index()+1);
});
来自:http://www.ozmonet.com/2013/01/08/tweaking-the-bootstrap-carousel/ 这是他的例子:http://www.ozmonet.com/photography/
但是
我想更新此代码以侦听哈希更改并更新轮播。
这是一个很好的参考:https://developers.google.com/tv/web/articles/location-hash-navigation#detect-loc-hash
这样做的目的是获取现有代码,并使其与浏览器的后退按钮一起使用。
您会注意到我链接到的演示 (http://www.ozmonet.com/photography/) 后退按钮更新了哈希值;但是,它只需要更新轮播。
这应该是一个可以被很多人大量使用的解决方案,因为它的使用潜力是巨大的。
更新:解决方案有效...
是的,我在下面有一个评论派对。
但是,看来我可能已经解决了。 http://jsfiddle.net/pcarguy/Pd4rv/
完整代码为:
// invoke the carousel
$('#myCarousel').carousel({
interval: false
});
var url = document.location.toString();
if (url.match('#')) {
// Clear active item
$('.carousel-inner div').removeClass('active');
// Activate item number #hash
var index = url.split('#')[1];
$('.carousel-inner div:nth-child(' + index + ')').addClass('active');
}
$('#myCarousel').bind('slid', function (e) {
// Update location based on slide (index is 0-based)
var item = $('#myCarousel .carousel-inner .item.active');
window.location.hash = "#"+parseInt(item.index()+1);
})
$(window).bind( 'hashchange', function(e) {
var item = $('#myCarousel .carousel-inner .item.active');
window.location.hash = "#"+parseInt(item.index()+1);
})
更新:不起作用
我猜还在等待答案!
【问题讨论】:
-
找到了一个潜在的好资源 - 它适用于 BS 标签而不是 BS 轮播,但它可以为标签 gist.github.com/badsyntax/2875426
-
注意到我引用的谷歌开发者页面和上面评论中的链接都使用:
$(window).bind( 'hashchange', function(e) { -
这是另一个选项卡解决方案 - 但不是轮播 jqueryfordesigners.com/enabling-the-back-button
-
这是一个你可以 fork 的小提琴jsfiddle.net/pcarguy/Pd4rv/3
-
这个解决方案对我来说效果很好 (stackoverflow.com/a/21113070/2422275)
标签: jquery twitter-bootstrap carousel hashchange