【发布时间】:2015-10-02 09:47:26
【问题描述】:
我有一个导航栏,每个按钮都会更改正文的背景。他们每个人都将其更改为不同的颜色。我为每个按钮创建了onmouseover 和onmouseout 函数来实现这一点。但是,我想知道是否有一种方法可以通过类引用它们来编写每个函数中的一个?他们都有相同的button 类。有没有一种方法可以将函数应用于某个类的所有元素?我的代码:
function whichButton(x) {
if (x==1)
return "red";
if (x==2)
return "green";
if (x==3)
return "blue";
if (x==4)
return "orange";
if (x==0)
return initBG;
}
button1.onmouseover = function() {
document.body.style.backgroundColor = whichButton(1);
}
button1.onmouseout = function() {
document.body.style.backgroundColor = whichButton(0);
}
button2.onmouseover = function() {
document.body.style.backgroundColor = whichButton(2);
}
button2.onmouseout = function() {
document.body.style.backgroundColor = whichButton(0);
}
button3.onmouseover = function() {
document.body.style.backgroundColor = whichButton(3);
}
button3.onmouseout = function() {
document.body.style.backgroundColor = whichButton(0);
}
button4.onmouseover = function() {
document.body.style.backgroundColor = whichButton(4);
}
button4.onmouseout = function() {
document.body.style.backgroundColor = whichButton(0);
}
initBG只是保存页面的初始背景。
我试过这个:
document.getElementsByClassName('button').onmouseover = function() {
document.body.style.backgroundColor = whichButton(1);
}
但它不会触发该功能。而且我想要做到这一点,我还需要有一种方法可以将元素的 ID 作为字符串读取,这样我就可以得到它的数字......
这更多是出于好奇而不是必要,只是想找到方法让我的代码变小!我可以看到这在许多应用程序中都很有用,所以我很想了解更多相关信息!
对应的HTML:
<div id="navbar">
<p id="button1" class="button">Red</p><p id="button2" class="button">Blue</p><p id="button3" class="button">Green</p><p id="button4" class="button">Orange</p>
</div>
【问题讨论】:
-
将事件监听器绑定到文档,并在回调中检查目标
-
请先添加相关的html
-
您有三个不同的功能..但是您要问如何将相同的功能应用于所有按钮?我在这里迷路了..请让要求更清楚
-
基本上,我已经写了 4 次完全相同的 onmouseover/onmouseout 函数。我觉得必须有一种方法只需要编写一次,并让每个按钮根据它的类而不是它的 ID 来触发它。代码可以正常工作,我只是想了解是否有更有效的方法来做我所做的事情。
-
document.getElementsByClassName('button') - 返回 HTML 集合,但基本上,您可以将其视为数组 - 因此,您可以循环遍历它...
标签: javascript css function class