几周前我构建了一个导航栏,然后才意识到我没有在上面设置 .active 类。现在,我在 JS 中动态构建了导航栏和链接,现在想为激活的任何一个提供相应的 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 代码的第二个片段中缺少/不完全正确,因为当我的链接处于活动状态时什么也没有发生。我得到了我想要得到的动画,但是一旦用户被重定向到那个特定的链接,它就会消失,所以你不知道你在哪个子页面上。
芜湖不芜
相关分类