How to toggle class using pure javascript in html

2019-01-18 01:42发布

I have a <div>, and I want to toggle its classes on hover.

Here is my code:

function a(){
    this.classList.toggle('first');
    this.classList.toggle('sec');
}
document.querySelector('#container').addEventListener('click', a );

I know there is no problem in my html or css. It is just that I have to change and put something in place of click, but I don't know what.

Please help!!

2条回答
干净又极端
2楼-- · 2019-01-18 01:43

While Tom Chung's approach definitely works, it's better to give mouseenter and mouseleave their own handler :

var container = document.querySelector('#container');

container.addEventListener('mouseenter', function(){
        this.classList.remove('first');
        this.classList.add('second');
})
container.addEventListener('mouseleave', function(){
        this.classList.add('first');
        this.classList.remove('second');
})
.first {
    background: green;
}

.second {
    background: orange;
}
<div id="container" class="first">
    TEST
</div>

(see also this Fiddle)

查看更多
We Are One
3楼-- · 2019-01-18 01:49

Hover event is called "mouseenter" instead of "click".

<script type="text/javascript">
    function a(){
        this.classList.toggle('first');
        this.classList.toggle('sec');
    }
    document.querySelector('#container').addEventListener('mouseenter', a )
    document.querySelector('#container').addEventListener('mouseleave', a )
</script>
查看更多
登录 后发表回答