如何更改导航栏当前页面的颜色

时间:2019-07-02 18:30:55

标签: javascript php html css

我能够获取导航栏来更改颜色,以使其处于悬停状态,活动状态和当前状态。问题是页面加载时会刷新导航栏,并且当前页面的颜色会还原。我相信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>

我希望导航栏将当前页面的颜色保持绿色。导航变为绿色,然后恢复为导航栏的默认灰色。

1 个答案:

答案 0 :(得分:1)

关键是要在页面加载时执行此操作,而不是在点击时加载。

简单地循环浏览,看看HREF是否与当前URL匹配。

<script>
    let current_url = document.location;
    document.querySelectorAll(".navbar .btn").forEach(function(e){
       if(e.href == current_url){
          e.classList += " current";
       }
    });
</script>