现行做法的问题在于,如果他们没有到场,就只会增加这一类。 这意味着,只有将原类别与所附“填充”类别相转换,不允许多个要素同时拥有“填充”类别。
在这方面,你如何能够实现理想行为:
1. 取消现有的“填满”类别:
Before adding the "-fill" class to the clicked element, you need to remove it from any other element that might have it. This ensures only one element has the active state at a time.
// Select all anchor elements within the navigation
const navLinks = document.querySelectorAll( .nav-link );
navLinks.forEach(link => {
// Remove any existing "-fill" class
link.classList.remove( bi-house-fill , bi-heart-fill , bi-envelope-fill );
});
2. 在点击元件中添加“填充”类别:
Now, when an anchor element is clicked, you can use classList.toggle to add the "-fill" class specific to the clicked icon.
navLinks.forEach(link => {
link.addEventListener( click , () => {
const icon = link.querySelector( i );
const iconClass = icon.classList[1]; // Get the second class (e.g., "bi-house")
icon.classList.toggle(`${iconClass}-fill`);
});
});
<>Explanation:
- We use
querySelectorAll
to select all anchor elements with the class nav-link.
- We loop through each link using
forEach
.
- Inside the loop, we use
classList.remove
to remove any existing "-fill" classes from the icon within the link. This ensures only one element has the active state.
- We add an event listener to each link for the
click
event.
- When a link is clicked, we use
querySelector
to get the icon element within the link.
- We then access the second class name of the icon using
classList[1]
. This assumes the icon class is the second class on the element.
- Finally, we use
classList.toggle
with a template literal to dynamically construct the class name to be toggled. This ensures the appropriate "-fill" class is added or removed based on the clicked icon.
这种办法确保,只有被点击的icon有“填充”类别,为运行中的导航项目提供所需的视觉反馈。