将 url 和 hash 与 bootstrap scrollspy 一起使用 [英] use url and hash with bootstrap scrollspy
问题描述
我有一个基于 twitter bootstrap 的导航菜单栏,我想应用 scrollspy 来突出显示.我使用普通的 php 包含将菜单包含到多个页面中.因此,我使用文件名和书签(例如 products.php#foo)链接到文件.
I have a nav menu bar based on twitter bootstrap that I want to apply scrollspy to for hightlighting. i include the menu into multiple pages using a normal php include. therefore I am linking to files using their filename plus bookmark (e.g. products.php#foo).
但是 scrollspy 希望 url 工作的方式是使用格式 my link</a>
,这样当 <div id="id-of-target">
滚动到视图中,根据 href 属性匹配 href 并将活动类放在其上.
but the way that scrollspy wants urls to work is to use the format <a href="#id-of-target">my link</a>
, so that when <div id="id-of-target">
scrolls into view, the href is matched based on the href attrib and gets the active class put on it.
这意味着如果我有一个像 <a href="products.php#my-catalogue">my catalogue</a>
这样的链接,那么它就不会匹配 id 并且该链接不会突出显示.
which means that if I have a link like <a href="products.php#my-catalogue">my catalogue</a>
then it won't match the id and the link won't highlight.
我不知道如何修改 scrollspy 使其只匹配 href 值中 #
之后的 id.
i couldn't work out how to modify scrollspy so that it only matches on the id after the #
in the href value.
推荐答案
新答案
(1) 您可以像这样向链接添加数据目标:
(1) You can add a data-target to your link like so:
<a href="products.php#my-catalogue" data-target="#my-catalogue">my catalogue</a>
(2) Bootstrap 使用导航链接中的 href 或 data-target 来查找页面上的目标区域.如果您有类似 products.php#my-catalogue
的内容,代码中的正则表达式检查器将失败.但是如果你事先做了修剪它会起作用
(2) Bootstrap uses either your href or data-target in your nav links to find the target regions on the page. If you have something like products.php#my-catalogue
the regular expression checker in the code will fail. But if you do a trim beforehand it will work
在滚动间谍引导程序代码中,您可以更改(在 ScrollSpy 的刷新"功能中):
In scroll spy bootstrap code you can change (in the "refresh" function in ScrollSpy):
.map(function () {
var $el = $(this)
, href = $el.data('target') || $el.attr('href')
, $href = /^#\w/.test(href) && $(href)
到
.map(function () {
var $el = $(this)
, href = $el.data('target') || $el.attr('href')
, trimmed = href.match(/#\w*/)[0]
, $href = /^#\w/.test(trimmed) && $(trimmed)
然后有类似的东西
<a href="products.php#my-catalogue">my catalogue</a>
应该没问题
旧答案
也许您可以尝试在 bootstrap js 代码中编辑滚动间谍选择器?
Maybe you could try editing the scroll spy selector in the bootstrap js code?
有一行(对我来说大约是 1442):
There is a line (around 1442 for me):
selector = this.selector
+ '[data-target="' + target + '"],'
+ this.selector + '[href="' + target + '"]'
如果改为
selector = this.selector
+ '[data-target="' + target + '"],'
+ this.selector + '[href="products.php' + target + '"]'
可以解决您的问题
这篇关于将 url 和 hash 与 bootstrap scrollspy 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!