用 Swup.js 突出显示当前 link
Highlight current link with Swup.js
我使用 Swup 进行页面转换,想知道如何突出显示当前活动的 link。假设我的页面结构如下:
<nav>
<a href="/page-1">Page 1</a>
<a href="/page-2">Page 2</a>
</nav>
<main id="swup">
<!-- content -->
</main>
每次 nav a
单击后,页面内容都会被替换,但我想为当前活动的 link 设置不同的样式。
感谢您的帮助!
您可以使用 Swup contentReplaced
挂钩来侦听已完成的页面加载,遍历与指定选择器匹配的所有链接,并检查它们的 href 是否与当前 url.
function swupActiveLinks(){
let currentPath = window.location.pathname;
let links = document.querySelectorAll('nav a'); // <- put your link selector here
for (const link of links) {
let linkPath = (new URL( link.href )).pathname;
link.ariaCurrent = linkPath == currentPath ? 'page' : false;
}
}
swup.on('contentReplaced', () => {
swupActiveLinks(); // trigger after swup
});
swupActiveLinks(); // trigger on page load
然后设置所有当前链接的样式:
nav a[aria-current=page]{
text-decoration: underline;
}
我使用 Swup 进行页面转换,想知道如何突出显示当前活动的 link。假设我的页面结构如下:
<nav>
<a href="/page-1">Page 1</a>
<a href="/page-2">Page 2</a>
</nav>
<main id="swup">
<!-- content -->
</main>
每次 nav a
单击后,页面内容都会被替换,但我想为当前活动的 link 设置不同的样式。
感谢您的帮助!
您可以使用 Swup contentReplaced
挂钩来侦听已完成的页面加载,遍历与指定选择器匹配的所有链接,并检查它们的 href 是否与当前 url.
function swupActiveLinks(){
let currentPath = window.location.pathname;
let links = document.querySelectorAll('nav a'); // <- put your link selector here
for (const link of links) {
let linkPath = (new URL( link.href )).pathname;
link.ariaCurrent = linkPath == currentPath ? 'page' : false;
}
}
swup.on('contentReplaced', () => {
swupActiveLinks(); // trigger after swup
});
swupActiveLinks(); // trigger on page load
然后设置所有当前链接的样式:
nav a[aria-current=page]{
text-decoration: underline;
}