简体   繁体   English

当我将鼠标悬停在它链接的部分时,我想更改超链接的类别

[英]I want to change class of Hyper link when i hover around the section which it is linked

How can I implement javascript for the code below that adds class="active" to hyper link when I move to the section, ie when I move to section it should add class="active" to About.我如何为下面的代码实现 javascript,当我移动到该部分时,将 class="active" 添加到超链接,即当我移动到部分时,它应该将 class="active" 添加到 About。 And also if I move to other section remove the class="active" from previous section and Add to the current section.而且,如果我移到其他部分,请从上一部分中删除 class="active" 并添加到当前部分。

 #s1 { display: flex; width: 100%; height: 500px; background: rgb(156, 78, 192); justify-content: center; align-items: center; } #s1 h1:hover { cursor: pointer; color: red; } #s2 { width: 100%; height: 500px; background: rgb(187, 82, 40); } #s3 { width: 100%; height: 500px; background: rgb(58, 56, 168); } #s4 { width: 100%; height: 500px; background: rgb(78, 54, 54); position: relative; }
 <div class="root"> <div class="nav"> <ul> <li><a href="#s1">Home</a></li> <li><a href="#s2">About</a></li> <li><a href="#s3">Contact</a></li> <li><a href="#s4">Project</a></li> </ul> </div> <section id="s1" id="top"><h1>hello</h1></section> <section id="s2"></section> <section id="s3"></section> <section id="s4"> <a href="#top">goto top</a> </section>

You can add an event listener to the click events in your nav and add/remove the 'active' class from the <li tags您可以向导航中的点击事件添加事件侦听器,并从<li标签中添加/删除“活动”类

 window.addEventListener('DomContentLoaded', () => { // listen for the DOM to finish loading document.querySelectorAll('.nav li a').forEach(el => { // get all the nav links together in a loop el.addEventListener('click', e => { // listen for the click event on the nav item document.querySelectorAll('.nav li').forEach(li => li.classList.remove('active')); // first remove all active classes from all navigation links e.target.closest('li').classList.add('active') // apply active class to the chosen nav }) }) })
 #s1 { display: flex; width: 100%; height: 500px; background: rgb(156, 78, 192); justify-content: center; align-items: center; } #s1 h1:hover { cursor: pointer; color: red; } #s2 { width: 100%; height: 500px; background: rgb(187, 82, 40); } #s3 { width: 100%; height: 500px; background: rgb(58, 56, 168); } #s4 { width: 100%; height: 500px; background: rgb(78, 54, 54); position: relative; } .active { background: #000; } .active a { color: #fff; }
 <div class="root"> <div class="nav"> <ul> <li><a href="#s1">Home</a></li> <li><a href="#s2">About</a></li> <li><a href="#s3">Contact</a></li> <li><a href="#s4">Project</a></li> </ul> </div> <section id="s1" id="top"> <h1>hello</h1> </section> <section id="s2"></section> <section id="s3"></section> <section id="s4"> <a href="#top">goto top</a> </section> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM