当使用绝对 url 而不是 # 锚链接时,我试图让 scrollspy 工作。
例如,我可以通过仅使用轻松运行 scrollspy<a href="#section1"></a>
我希望能够通过使用运行 scrollspy<a href="http://myurl.com/#section1"></a>
这样做的原因,是主页上的主导航是scorllspy,但是博客不是主页的一部分。当访问博客然后单击主页上的某个链接时,您会被路由到http://myurl.com/blog/#section1
而不是主页 ID。
我找到了这个解决方案(使用 url 和 hash with bootstrap scrollspy),但无法让它完全发挥作用。经过一些调整和一系列正则表达式组合后,我可以让它将活动类添加到第一个菜单项,但它不会刷新。
关于让它发挥作用的任何想法?有没有我应该使用的替代 js 库?
感谢特洛伊的解决方案
jQuery(function($){
// local url of page (minus any hash, but including any potential query string)
var url = location.href.replace(/#.*/,'');
// Find all anchors
$('.nav-main').find('a[href]').each(function(i,a){
var $a = $(a);
var href = $a.attr('href');
// check is anchor href starts with page's URI
if (href.indexOf(url+'#') == 0) {
// remove URI from href
href = href.replace(url,'');
// update anchors HREF with new one
$a.attr('href',href);
}
// Now refresh scrollspy
$('[data-spy="scroll"]').each(function (i,spy) {
var $spy = $(this).scrollspy('refresh')
})
});
$('body').scrollspy({ target: '.nav-main', offset: 155 })
});
我添加$('body').scrollspy({ target: '.nav-main', offset: 155 })
是为了在刷新 scrollspy 后重新应用数据偏移量。经过反复试验,这是我能找到的唯一解决方案。