gpt4 book ai didi

javascript - 使用 JavaScript 添加类

转载 作者:IT王子 更新时间:2023-10-29 03:12:32 25 4
gpt4 key购买 nike

我正在编写一些普通的 JavaScript 来创建一个漂亮的导航菜单。我坚持要添加一个事件类。

我按类名而不是 id 获取元素。如果用 id 替换,下面的代码可以工作,但是,我需要它应用于多个元素。

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 的答案。

最佳答案

document.getElementsByClassName 返回一个节点列表。因此,您必须遍历列表并将事件绑定(bind)到各个元素。像这样...

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 - 使用 JavaScript 添加类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17944843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com