Bootstrap 轮播 - 链接到特定幻灯片
Bootstrap 轮播 - 链接到特定幻灯片
我在展示当前幻灯片编号和链接到当前页面的特定幻灯片方面找到了很多帮助,但我的问题有点不同...
我需要能够链接到另一个页面中的一个特定幻灯片。因此我会有类似这样的内容:在\'index.html\' 上有这样一个代码: a href=\"page2.html#slide2\"
当用户点击此链接时,它将带他们到\'page2.html\'页面,并显示第二张幻灯片。
感谢任何帮助。
谢谢,
Alex
admin 更改状态以发布 2023年5月23日
全新升级版测试一个有效的整数,并默认为0:
function qs(key) { key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars var match = location.search.match(new RegExp("[?&]" + key + "=([^&]+)(&|$)")); var slide = match && decodeURIComponent(match[1].replace(/\+/g, " ")); if (Math.floor(slide) == slide && $.isNumeric(slide)) return parseInt(slide); else return 0; } $('#myCarousel').carousel(qs('slide'));
您可以使用查询字符串,如... www.example.com?slide=2
$(document).ready(function(){ function getParameterByName(name) { name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]"); var regex = new RegExp("[\\?&]" + name + "=([^]*)"), results = regex.exec(location.search); return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); } $('#myCarousel').carousel(getParameterByName('slide')); });
或者使用哈希值,如... www.example.com#2
$(document).ready(function(){ $('#myCarousel').carousel(window.location.hash.substring(1)); });
无论您使用哪种方式,都必须从 URL 中提取一个整数,因此您可能需要使代码更加健壮,以确保只有在获得有效的整数并且检查它是否在 carousel 中存在的幻灯片数量的范围内时才移动 carousel。
.carousel(number)
将 carousel 循环到特定帧(基于0,类似于数组)。