根據當前頁面 URL(window.location.pathname)與導航連結 href 比對,為匹配的 <li> 加上 .on 類別,配合 CSS 實現高亮。提供兩種寫法:迴圈比對與自定義函式封裝。
var v = window.location.pathname;
$(".hd ul li a").each(function(i) {
var vherf = $(this).attr("href");
if (v == vherf) {
$(".hd ul li").eq(i).addClass("on");
} else {
$(".hd ul li").eq(i).removeClass("on");
}
});
nav(name, csskey, cssvalue)function nav(name, csskey, cssvalue) {
var url = window.location.pathname + window.location.search;
$(name).each(function() {
var v1 = "/" + $(this).attr("href");
if (v1 == url) {
$(this).css(csskey, cssvalue); // 直接設定樣式
}
});
}
// 使用
window.onload = function() {
nav(".top ul li a", "background-color", "rgb(255,89,0)");
};
class="active",無需手動比對 URL。.hd ul li.on a { color: #fff; background: #ff5900; }