我的侧边栏使用了以下代码,以便能够设置活动子页面,并在刷新页面时正确显示侧边栏。
如果我添加"#"符号到子页面的href中,但当将href更改为其他内容并删除"#"时不起作用。的象征。假设我想将href设置为"/contactpage/。在下面的代码中,我如何指示选择任何href而不仅仅是包含哈希符号的href ?
<script>
(() => {
'use strict'
function setActiveItem() {
const { hash } = window.location
if (hash === '') {
return
}
const link = document.querySelector(`.d-flex a[href="${hash}"]`)
if (!link) {
return
}
const active = document.querySelector('.d-flex .active')
const parent = link.parentNode.parentNode.previousElementSibling
link.classList.add('active')
if (parent.classList.contains('collapsed')) {
parent.click()
}
if (!active) {
return
}
const expanded = active.parentNode.parentNode.previousElementSibling
active.classList.remove('active')
if (expanded && parent !== expanded) {
expanded.click()
}
}
setActiveItem()
window.addEventListener('hashchange', setActiveItem)
})()
</script>
// Select anything with an "href" attribute, regardless of its value
document.querySelectorAll('[href]')
// Select only the first link with the current page's path ("active" link)
const currentPath = window.location.pathname
document.querySelector(`a[href="${currentPath}"]`)
// Select the currently active path including the hash
const currentPathWithHash = window.location.pathname + window.location.hash
document.querySelector(`a[href="${currentPathWithHash}"]`)
为了避免当所有链接都不包含哈希时的问题,只需删除代码的前几行直到const link = ...
,它应该被上面的一个选项替换(编辑以适应您的需要)。
我还注意到,如果active
也是当前链接,您将首先向其添加active
类,然后在稍后的代码中删除它。像这样切换顺序以避免:
active.classList.remove('active')
link.classList.add('active')
注意,如果页面上可能有多个指向当前路径的链接,您可能应该添加更多的选择器,例如用于目标链接的类名。当然,除非您想要使用该路径定位任何链接,在这种情况下只需使用document.querySelectorAll
。你的似乎是在.d-flex
容器下,所以把它添加到我的例子中。