幾周前我構建了一個導航欄,然后才意識到我沒有在上面設置 .active 類?,F在,我在 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 代碼的第二個片段中缺少/不完全正確,因為當我的鏈接處于活動狀態時什么也沒有發生。我得到了我想要得到的動畫,但是一旦用戶被重定向到那個特定的鏈接,它就會消失,所以你不知道你在哪個子頁面上。
為動態創建的鏈接 JS 設置一個 .active 類
白板的微信
2023-05-11 14:33:03