How to toggle class using pure javascript in html

前端 未结 2 1726
借酒劲吻你
借酒劲吻你 2020-12-03 02:22

I have a

, and I want to toggle its classes on hover.

Here is my code:

function a(){
    this.classList.toggle(\'first\');
           


        
2条回答
  •  天命终不由人
    2020-12-03 02:50

    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;
    }
    TEST

    (see also this Fiddle)

提交回复
热议问题