【发布时间】:2019-11-13 10:42:23
【问题描述】:
我能够让导航栏更改悬停、活动和当前的颜色。问题是当页面加载时它会刷新导航栏并且当前页面颜色会恢复。我相信 javascript 正在按预期工作。
我找到了一种方法,其中每个网页都有自己的导航栏,这不是最好的编码方法,只有在网站只有几个页面时才会使用。
/*
* https://www.w3schools.com/howto/howto_js_active_element.asp
*/
// Get the container element
var btnContainer = document.getElementById("navbar");
// Get all buttons with class="btn" inside the container
var btns = btnContainer.getElementsByClassName("btn");
// Loop through the buttons and add the active class to the current/clicked button
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("current");
// If there's no current class
if (current.length > 0) {
current[0].className = current[0].className.replace(" current", "");
}
// Add the current class to the current/clicked button
this.className += " current";
});
}
/* Change background color of navbar links on hover */
.btn:hover {
background-color: #FFFF00;
/* Yellow */
color: #000000;
/* Black */
}
/* Change background color of navbar links on active */
.btn:active {
background-color: #FF0000;
/* Red */
color: #000000;
/* Black */
}
/* Change background color of navbar links for current page */
.btn.current {
background-color: #006600;
/* Green */
color: #FFFFFF;
/* White */
}
<nav>
...
<div id="navbar" class="navbar">
<div class="dropdown">
<button class="dropbtn"><a class="btn" href="index.php">Home</a>
<i class="fa fa-caret-down"></i>
</button>
</div>
<div class="dropdown">
<button class="dropbtn"><a class="btn" href="PlanYourVisit.php">New Here</a>
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdownContent">
<a class="btn" href="PlanYourVisit.php">Plan Your Visit</a>
<a class="btn" href="YourKids.php">Your Kids</a>
<a class="btn" href="TimeLocation.php">Time and Location</a>
</div>
</div>
...
</div>
</div>
</nav>
我希望导航栏保持当前页面的颜色为绿色。导航变为绿色,然后恢复为导航栏的默认灰色。
【问题讨论】:
-
你有理由使用 JS 吗?由于该站点已经是 PHP(我假设),因此您可以参考此答案以将按钮的 URL 与实际 URL 进行比较,并基于此输出一个类。 stackoverflow.com/questions/7118823/…
标签: javascript php html css