问题
My active (opened) links are highlighted with JS .
<script type="text/javascript">
$(document).ready(function(){
$("a.nav1").click(function() {
$(".active").removeClass("active");
$(this).addClass("active");
});
});
</script>
links example
<div id="navigation">
<ul>
<li><a class="nav1" data-tab="#home" id="link-home"href="#home">Home</a></li>
<li><a class="nav1" data-tab="#football" id="link-football" href="#football">Football</a></li>
<li><a class="nav1" data-tab="#hockey" id="link-hockey"href="#hockey">Hockey</a></li>
</ul>
</div>
But clicking on the back button or refreshing the page doesn't remove and/or add the .active
class to the appropriate link.
So, my question is, how to use the History API or history.js to change the "active" link appropriately when the page is refreshed or when the back button is pressed?
回答1:
You can do it easily
<script type="text/javascript">
var loc = window.location.pathname;
$('#navigation').find('a').each(function() {
$(this).toggleClass('active', $(this).attr('href') == loc);
});
</script>
css:
#navigation a.active{color: red}
OR
You can see this answer Store a clicked link state using jQuery?
来源:https://stackoverflow.com/questions/23252490/how-to-use-the-history-api-or-history-js-to-change-the-active-link-appropriate