[英]How to add and remove active class using js
This is my menu html How can i add active class and remove active class using js : 这是我的菜单html如何使用js添加活动类和删除活动类:
<div class="sidenav">
<a href="{{url('/home')}}" class="sidemenu"><i class="fa fa-home"></i>
</br>Users</a>
<a href="{{route('user-channel.index')}}" class="sidemenu"><i class="fa
fa-plus"></i></br>Channel</a>
</div>
Something like this should work. 这样的事情应该起作用。
var sideNav = document.querySelector(".sidenav"); sideNav.addEventListener("click", function(e) { e.stopPropagation(); e.preventDefault(); if (e.target.classList.contains("sidemenu")) { for (let i = 0; i <= sideNav.children.length - 1; i++) { if (sideNav.children[i].classList.contains("active")) { sideNav.children[i].classList.remove("active"); } } e.target.classList.add("active"); } });
.active { color: blue; background-color: yellow; } a { text-decoration: none; }
<div class="sidenav"> <a href="" class="sidemenu"><i class="fa fa-home"></i> </br>Users</a> <a href="" class="sidemenu"><i class="fa fa-plus"></i></br>Channel</a> </div>
this how you can do it. 这是你怎么做的。
const linkList = document.querySelectorAll('.sidemenu');
const link = document.querySelector('.sidemenu');
link.addEventListener('click', e => {
let $this = e.target;
linkList.forEach(ele => {
ele.classList.remove('active');
});
$this.classList.add('active');
});
javascript interpreter in browser read script from top to bottom so first we get the list of items have calss .sidemenu
by declaring consistent variable linkList
then we get the one element node by declaring another consistent variable link
after we make click event inside we declare variable $this
to refer to the event target (the element i have clicked) then we make loop on all links that have .sidemenu
class to remove class active
then out side the loop and in event block we add active
class to the target (the element i have just clicked) 浏览器中的javascript解释器从上到下读取脚本,因此首先我们通过声明一致的变量linkList
获得具有calss .sidemenu
的项目列表,然后在声明变量内部声明了变量$this
之后,通过声明另一个一致的变量link
获得一个元素节点$this
是指事件目标(我单击的元素),然后对所有具有.sidemenu
类的链接进行循环,以删除active
类,然后在循环之外,在事件块中,将active
类添加到目标(元素i刚刚点击)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.