【问题标题】:Add Remove Active Class Based On URL根据 URL 添加删除活动类
【发布时间】:2023-01-22 02:46:25
【问题描述】:

它只是在/上传/链接上的主页按钮上工作,不适用于其他按钮,有人可以修复它吗? 当我在其他按钮上添加此 href (/upload/) 时,它可以工作,但不能添加到其他页面。如果有人帮助,我正在使用带有 DataLife Engine 的本地主机。

const currentLocation = location.href;
const menuItem = document.querySelectorAll('.left_global a');
const menuLength = menuItem.length
for (let i = 0; i<menuLength; i++){
  if(menuItem[i].href === currentLocation){
    menuItem[i].className = "activemenu"
  }
} 
.left_global {
    position: fixed;
    z-index: 500;
    top: 0;
    left: 0;
    right: 0;
    /*  */
    height: 100%;
    width: 110px;
    background-color: black;
    backdrop-filter: blur(30px);
    box-shadow: 0 0 5px #ffffff14;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
  }
 .left_global a.activemenu {
  background: #ffffff29;
}
  .left_global a {
    padding: 15px 10px 15px 15px;
    text-decoration: none;
    font-size: 13px;
    color: white;
    display: block;
    position: relative;
    text-align: center;
    width: 100%;
  }

  .left_global a:hover {
    background: #ffffff29;
  }
<section class="left_global">
  <a href="/upload/">
    <div>Home</div></a>
  <a href="/upload/movie">
    <div>Movie</div></a>
  <a href="/upload/tv-shows">
    <div>TV-Shows</div></a>
  <a href="/upload/actor">
    <div>Actors</div></a>
  <a href="/upload/trailer">
    <div>Trailers</div></a>
  <a href="/upload/index.php?do=static&page=application">
    <div>Application</div></a>
</section>

【问题讨论】:

    标签: javascript menu navbar


    【解决方案1】:

    您遇到的问题可能是由于 location.href 属性只返回当前路径名,而不是完整的 URL。因此,当您将它与菜单项的 href 属性进行比较时,它只匹配 URL 的第一部分(“/upload/”)。

    一种解决方案是在脚本中使用 window.location.pathname 而不是 location.href,这将为您提供当前 url 的路径名。

    const currentLocation = window.location.pathname;
    const menuItem = document.querySelectorAll('.left_global a');
    const menuLength = menuItem.length
    for (let i = 0; i<menuLength; i++){
      if(menuItem[i].href === currentLocation){
        menuItem[i].className = "activemenu"
      }
    }
    

    另一种解决方案是使用 String.prototype.endsWith() 方法检查字符串是否以指定的搜索字符串结尾,这将检查 url 路径名是否以菜单项 url 结尾。

    const currentLocation = window.location.pathname;
    const menuItem = document.querySelectorAll('.left_global a');
    const menuLength = menuItem.length
    for (let i = 0; i<menuLength; i++){
      if(currentLocation.endsWith(menuItem[i].href)){
        menuItem[i].className = "activemenu"
      }
    }
    

    以上两种解决方案都应该可以帮助您解决问题。

     

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-31
      • 2019-07-09
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 2021-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多