クリックした現在のメニューを強調表示したい。私はCSSを使用していますが、現在は機能しています。
ここに私のcssコードがあります:
#sub-header ul li:hover{ background-color: #000;}
#sub-header ul li:hover a{ color: #fff; }
#sub-header ul li.active{ background-color: #000; }
#sub-header ul li.active a{ color: #fff; }
ここに私のhtmlがあります:
<div id="sub-header">
<ul>
<li> <a href="index.php">Home</a> </li>
<li> <a href="contact.php">Contact Us</a> </li>
<li> <a href="about.php">About Us</a> </li>
</ul>
</div>
これは、ホバーしたときにメニューがアクティブな場合に私が好むものです
ホバーは大丈夫です。問題は、メニューをクリックした後、黒い地面が表示されないことです
@ジョナサン、私はすでにそれを解決しており、あなたが与えたものよりも簡単です。
これが私の答えです:
$(function(){
// this will get the full URL at the address bar
var url = window.location.href;
// passes on every "a" tag
$("#sub-header a").each(function() {
// checks if its the same on the address bar
if(url == (this.href)) {
$(this).closest("li").addClass("active");
}
});
});
次に、私のcssファイルで:
.active { background-color: #000; }
/* to override the existing css for "a" tag */
#sub-header .active a{ color: #fff; }