如何将活动 class 添加到菜单(基于 url 哈希)
How to add active class to menu (based on url hash)
我有一个锚link菜单:
<ul>
<li class="anchorX"><a href="#anchorX">Bla</a></li>
<li class="anchorY"><a href="#anchorY">Bli</a></li>
<li class="anchorZ"><a href="#anchorZ">Blu</a></li>
</ul>
现在我想根据 url.
中的当前哈希向 li
元素添加一个活动的 class
因为不会重新加载页面,所以我尝试编写一个函数来监听 te url:
$(window).on('hashchange', function() {
//get the hash
var adressBarHash = window.location.hash.replace("#",".");
//now apply the class active to the link which contains the same hash as a class
$("ul").find(adressBarHash).addClass( "active" );
});
我的想法是将 url 中的散列与 class 相匹配。但是我无法让它工作。
更好的方法是将地址栏中的散列与 href 标签中的散列相匹配,但那超出了我的范围。
$(window).on('hashchange', function() {
var adressBarHash = window.location.hash;
$('[href*=' + adressBarHash + ']').addClass('active')
});
编辑:哎呀,没看到你想要它在 li
你快搞定了。
$(window).on('hashchange', function() {
let hash = window.location.hash;
$('a').closest('li').removeClass('active');
$('a[href="' + hash + '"]').closest('li').addClass('active');
});
我有一个锚link菜单:
<ul>
<li class="anchorX"><a href="#anchorX">Bla</a></li>
<li class="anchorY"><a href="#anchorY">Bli</a></li>
<li class="anchorZ"><a href="#anchorZ">Blu</a></li>
</ul>
现在我想根据 url.
中的当前哈希向li
元素添加一个活动的 class
因为不会重新加载页面,所以我尝试编写一个函数来监听 te url:
$(window).on('hashchange', function() {
//get the hash
var adressBarHash = window.location.hash.replace("#",".");
//now apply the class active to the link which contains the same hash as a class
$("ul").find(adressBarHash).addClass( "active" );
});
我的想法是将 url 中的散列与 class 相匹配。但是我无法让它工作。
更好的方法是将地址栏中的散列与 href 标签中的散列相匹配,但那超出了我的范围。
$(window).on('hashchange', function() {
var adressBarHash = window.location.hash;
$('[href*=' + adressBarHash + ']').addClass('active')
});
编辑:哎呀,没看到你想要它在 li
你快搞定了。
$(window).on('hashchange', function() {
let hash = window.location.hash;
$('a').closest('li').removeClass('active');
$('a[href="' + hash + '"]').closest('li').addClass('active');
});