add class with JavaScript

前端 未结 7 2009
傲寒
傲寒 2020-12-29 02:38

I am writing some vanilla JavaScript to create a nice navigation menu. I am stuck on adding an active class.

I am getting elements by class name NOT by id. The belo

7条回答
  •  有刺的猬
    2020-12-29 02:52

    In your snippet, button is an instance of NodeList, to which you can't attach an event listener directly, nor can you change the elements' className properties directly.
    Your best bet is to delegate the event:

    document.body.addEventListener('mouseover',function(e)
    {
        e = e || window.event;
        var target = e.target || e.srcElement;
        if (target.tagName.toLowerCase() === 'img' && target.className.match(/\bnavButton\b/))
        {
            target.className += ' active';//set class
        }
    },false);
    

    Of course, my guess is that the active class needs to be removed once the mouseout event fires, you might consider using a second delegator for that, but you could just aswell attach an event handler to the one element that has the active class:

    document.body.addEventListener('mouseover',function(e)
    {
        e = e || window.event;
        var oldSrc, target = e.target || e.srcElement;
        if (target.tagName.toLowerCase() === 'img' && target.className.match(/\bnavButton\b/))
        {
            target.className += ' active';//set class
            oldSrc = target.getAttribute('src');
            target.setAttribute('src', 'images/arrows/top_o.png');
            target.onmouseout = function()
            {
                target.onmouseout = null;//remove this event handler, we don't need it anymore
                target.className = target.className.replace(/\bactive\b/,'').trim();
                target.setAttribute('src', oldSrc);
            };
        }
    },false);
    

    There is some room for improvements, with this code, but I'm not going to have all the fun here ;-).

    Check the fiddle here

提交回复
热议问题