问题
I'm using to use jQuery to add some effects on the nav link when I'm on the different pages. But every time I jump to the next page, it will refresh the website. How can I manage to have effect wherever the page I am on?
Here's a example.
<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");
});
});
Many thanks!
回答1:
You are currently just adding a class to your nav-link
items on the click
event. That will only work if you stay on the same page. As soon as you load another page, that state gets lost. You need to add the same functionality (of adding the active
class) on pageload.
First you would need to get the current path with
let path = window.location.pathname;
Assuming your URL is https://www.example.com/index.html
, window.location.pathname
will return /index.html
Then you need to compare it with the href
attribute in your nav-link
$('.nav-link').each(function() {
if(path === $(this).attr('href')) {
$(this).addClass('active');
}
});
In total:
$(document).ready(function() {
let path = window.location.pathname;
$('.nav-link').each(function() {
if(path === $(this).attr('href')) {
$(this).addClass('active');
}
});
});
回答2:
One options would be to store the link text in localStorage
and use that to add your styling to the appropriate link after the DOM loads after the navigation:
$(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
}
});
}
});
You can also use sessionStorage
or a cookie
.
来源:https://stackoverflow.com/questions/64915536/how-do-i-focus-on-the-item-in-my-navbar-when-i-changes-to-a-different-page