首页 > 解决方案 > 为动态创建的链接 JS 设置 .active 类

问题描述

几周前我建立了一个导航栏,然后才意识到我没有在上面设置 .active 类。现在,我在 JS 中动态构建了导航栏和链接,现在想为任何一个处于活动状态的 CSS 提供相应的 CSS。

这就是我在 JS 中构建导航栏的方式:

let womensNav = document.createElement("ul");
womensNav.classList.add("womensNav");

const el1 = document.createElement("li");
el1.innerHTML = "<a>Jeans</a>";
el1.addEventListener("click", (e) => {
      document.location.href =
        "https://www.martadolska.com/product-category/women/womens-jeans";
});

womensNav.appendChild(el1);
document.querySelector(".ast-woocommerce-container").appendChild(womensNav);

我有多个链接,但为此我不需要全部显示。所以现在的目标是构建一个通用函数,为导航栏中的活动元素提供相应的类。

document.querySelectorAll("#womensNav li").forEach(function (ele) {
      ele.addEventListener("click", function (e) {
        e.preventDefault();
        document
          .querySelectorAll("#womensNav li a.active")
          .forEach((ele) => ele.classList.remove("active"));
        ele.parentNode.classList.toggle("active");
      });
    });

这就是我的 CSS 的样子:

.womensNav li a:hover {
  color: var(--main-text-color);
  text-decoration: line-through darkred solid;
}
.womensNav li a::before {
  content: "";
  position: absolute;
  width: 100%;
  height: 2px;
  bottom: 7px;
  left: 0;
  background-color: #b22222;
  visibility: hidden;
  transform: scaleX(0);
  transition: all 0.3s ease-in-out 0s;
}
.womensNav li a:hover::before {
  visibility: visible;
  transform: scaleX(1);
}
.womensNav li a:active::before {
  content: "";
  position: absolute;
  width: 100%;
  height: 2px;
  bottom: 10px;
  left: 0;
  background-color: #b22222;
}

// up until this point everything works
.active {
  text-decoration: line-through darkred solid;
}

我猜想在 JS 代码的第二个片段中缺少/不完全正确,因为当我的链接处于活动状态时没有发生任何事情。我得到了我想要的动画,但是一旦用户被重定向到该特定链接,它就会消失,所以你不知道你在哪个子页面上。

标签: javascriptcssdynamichyperlink

解决方案


这是错误的

ele.parentNode.classList.toggle("active");

“ele”是<li>,您正在<ul>通过parentNode将“活动”类添加到,可能会更好地使用单击中的“e”事件并使用e.target,然后尝试在<a>或使用上设置活动类childNode/children 获取你的<a>


推荐阅读