JavaScript 如何根据当前页面/URL选择class=“selected”

JavaScript 如何根据当前页面/URL选择class=“selected”

根据当前页面/URL选择class =“selected”非常重要,特别是在为网站设计导航栏时,这样访问者就可以知道他们在网站的哪个页面上。

方法: 根据当前页面/URL选择class =“selected”:

  • 编写你的HTML代码。
  • 编写所选类的CSS
  • 在javascript中,使用location.href找到您的页面的当前位置。
  • 现在使用document.querySelector函数将所有a标签保存在一个变量(比如说“Items”)中。
  • 遍历Items并将其位置与当前页面URL进行比较。
  • 如果Items的位置与页面的当前位置匹配,则将当前a标签类添加到所选类中。

语法:

const currentLocation = location.href

示例:

这段代码应该粘贴到所有四个文件中。

<html> 
  <head> 
    <style> 
      a { 
        color: #000; 
        text-decoration: none; 
      } 
  
      .nav { 
        padding: 10px; 
        border: solid 1px #c0c0c0; 
        border-radius: 5px; 
        float: left; 
      } 
      .nav li { 
        list-style-type: none; 
        float: left; 
        margin: 0 10px; 
      } 
      .nav li a { 
        text-align: center; 
        width: 55px; 
        float: left; 
      } 
      .nav li a.selected { 
        background-color: green; 
        color: #fff; 
        font-weight: bold; 
      } 
    </style> 
  </head> 
  
  <body> 
    <ul class="nav"> 
      <li><a href="home.html">Home</a></li> 
      <li>|</li> 
      <li><a href="gfg.html">GFG</a></li> 
      <li>|</li> 
      <li><a href="about.html">About</a></li> 
      <li>|</li> 
      <li><a href="contact.html">Contact</a></li> 
    </ul> 
  </body> 
  <script type="text/javascript"> 
    const currentLocation = location.href; 
    const Items = document.querySelectorAll("a"); 
    const Length = Items.length; 
  
    for (let i = 0; i < Items.length; i++) { 
      if (Items[i].href === currentLocation) { 
        Items[i].className = "selected"; 
      } 
    } 
  </script> 
</html> 

输出:

JavaScript 如何根据当前页面/URL选择class=“selected”

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程