用javascript添加类 [英] add class with javascript

查看:77
本文介绍了用javascript添加类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我正在写一些vanilla javascript来创建一个漂亮的导航菜单。我坚持添加一个活动类。

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

我通过类名而不是id获取元素。下面的代码工作,如果替换为By,但是,我需要它适用于多个元素。

I am getting elements by class name NOT by id. The below code works if substituted with By Id, however, I need it to apply to more than one element.

HTML

<img class="navButton" id="topArrow" src="images/arrows/top.png" />
<img class="navButton" id="rightArrow" src="images/arrows/right.png" />

JS

var button = document.getElementsByClassName("navButton");

button.onmouseover = function() {
    button.setAttribute("class", "active");
    button.setAttribute("src", "images/arrows/top_o.png");
}

没有答案包含jquery ...

No answers contain jquery please...

推荐答案

document.getElementsByClassName 返回节点列表。所以你必须遍历列表并将事件绑定到单个元素。像这样...

document.getElementsByClassName returns a node list. So you'll have to iterate over the list and bind the event to individual elements. Like this...

var buttons = document.getElementsByClassName("navButton");

for(var i = 0; i < buttons.length; ++i){
    buttons[i].onmouseover = function() {
        this.setAttribute("class", "active");
        this.setAttribute("src", "images/arrows/top_o.png");
    }
}

这篇关于用javascript添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆