【发布时间】:2021-01-27 20:10:48
【问题描述】:
几周前我建立了一个导航栏,但我意识到我没有在上面设置 .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 代码的第二个 sn-p 中缺少/不完全正确,因为当我的链接处于活动状态时什么都没有发生。我得到了我想要的动画,但是一旦用户被重定向到该特定链接,它就会消失,所以你不会知道你在哪个子页面上。
【问题讨论】:
标签: javascript css dynamic hyperlink