首页 > 解决方案 > 基于 url 或子目录突出显示当前导航选项卡

问题描述

我在我们网站的左侧创建了一个垂直导航。我们希望.item根据用户查看内容的子目录来更改 a 的背景颜色。因此,如果有人点击 nav .item,href 会将他们重定向到一个页面,我们希望它.item突出显示一个独特的十六进制颜色,我们可以为每个 nav 自定义.item。所有 6 个导航项目都有不同的颜色。

需要澄清的一点是,有时人们可能会访问我们的网站而无需单击导航项。我希望导航项仍然基于人们正在查看内容的当前子目录突出显示。这有助于他们轻松识别他们在哪里,以及如果他们导航到社区的其他部分,如何返回。此外,如果一个人进行全局搜索并偶然发现了我们 6 个主要区域之一的内容,我们希望导航菜单能够立即识别他们当前的位置(基于 url)并突出显示该导航.item在我们的垂直导航栏中突出显示该导航。

Javascript或Jquery是要走的路吗?任何帮助,将不胜感激!!

这是一个小提琴包含所有代码

示例 CSS:

.navback {
  position: fixed;
  top: 0;
  left: 0px;
  width: 100px;
  height: 100%;
  background: #283237;
  z-index: 4;
}

.navbar {
  position: fixed;
  top: 44px;
  left: 0px;
  width: 100px;
  height: 60vh;
  background: #283237;
  display: flex;
  z-index: 5;
  flex-direction: column;
}

.topbar {
  border-top: 1px solid #000;
  top: 44px;
}

.navbar .item {
  flex: 1;
  text-align: center;
  display: flex;
  justify-content: center;
  flex-direction: column;
  padding-top: 40px;
  padding-bottom: 40px;
  max-height: 100px;
  z-index: 5;
}

.navbar .item div.label {
  color: #fff;
  position: relative;
  top: 5px;
  font-size: 13px;
  font-family: -apple-system, BlinkMacSystemFont, Helvetica, Arial, "Segoe UI", sans-serif;
  transition: all 300ms cubic-bezier(0.68, -0.55, 0.27, 1.55);
  left: -100px;
}

示例 HTML:

 <div class="topbar"></div>
  <div class="navback leftnav">
<div class="navbar">
  <div class="item hvr-shrink">
    <a href="https://community.canopytax.com/">
    <div>
        <img src="https://png.icons8.com/ios/35/ffffff/home.png"/>
      <div class="label">Home</div>
    </div>
  </a>
  </div>

  <div class="item hvr-shrink">
    <a href="https://community.canopytax.com/community-central/">
    <div>
      <img src="https://png.icons8.com/ios/40/ffffff/conference-call.png">
      <div class="label">Central</div>
    </div>
  </a>
  </div>

标签: htmlcssbackground-colornavigationbar

解决方案


JS/jQuery

// get the first directory by splitting "/dir/path/name" into an array on '/'
// get [1] instead of [0] b/c the first should be blank. wrap in /s.
hereDir = "/" + window.location.pathname.split("/")[1] + "/";

// rebuild the URL since you're using absolute URLs (otherwise just use hereDir)
hereUrl = window.location.protocol + "//" + window.location.host + hereDir;

$(".item")
    .find("[href^='" + hereUrl + "']")
        .closest(".item").addClass("here");

注意.find("[href^=...]")选择以您要查找的内容开头的内容。

CSS

/* now use .here to style */
.item.here {
    background-color: purple;
}
.item.here .label {
    font-weight: bold;
}

推荐阅读