当我在不同的页面上时,我会使用jQuery在导航链接上添加一些效果。但每次我跳转到下一页时,它都会刷新网站。我怎么才能在我所在的页面上取得效果呢?
下面是一个例子。
<nav class="control-panel">
<ul>
<li class="nav-item">
<a href="./index.html" class="nav-link">Dashboard</a>
</li>
<li class="nav-item">
<a href="./assignment.html" class="nav-link">Assignment</a>
</li>
</ul>
</nav>.nav-link{
color: green;
}
.nav-link--active{
color: red;
}$(document).ready(function () {
$(".nav-link").click(function (e) {
$(this)
.addClass("nav-link--active")
.parent()
.siblings()
.find(".nav-link")
.removeClass("nav-link--active");
});
});非常感谢!
发布于 2020-11-20 00:29:38
您当前只是在click事件上向nav-link项添加了一个类。这只有在你保持一致的情况下才会起作用。一旦您加载另一个页面,该状态就会丢失。您需要在页面加载上添加相同的功能(添加active类)。
首先,您需要使用以下命令获取当前路径
let path = window.location.pathname;假设您的URL是https://www.example.com/index.html,window.location.pathname将返回/index.html
然后,您需要将其与nav-link中的href属性进行比较
$('.nav-link').each(function() {
if(path === $(this).attr('href')) {
$(this).addClass('active');
}
});总而言之:
$(document).ready(function() {
let path = window.location.pathname;
$('.nav-link').each(function() {
if(path === $(this).attr('href')) {
$(this).addClass('active');
}
});
});发布于 2020-11-20 00:23:37
一种选择是将链接文本存储在localStorage中,并在导航后加载DOM后使用它将样式添加到适当的链接:
$(document).ready(function () {
$(".nav-link").click(function (e) {
//Save the link text in localStorage for use in styling after a page refresh/navigation
localStorage.setItem('linktext', $(this).text());
});
//If localStorage has the key, set the appropriate link style
if(localStorage.getItem("linktext") !== null){
$('.nav-link').each(function(){
if($(this).text() === localStorage.getItem("linktext")){
//Set your styling on this anchor element
}
});
}
});您也可以使用sessionStorage或cookie。
https://stackoverflow.com/questions/64915536
复制相似问题