一个javascript函数可以应用于某个CSS类的所有元素吗?

Can a javascript function apply to all elements of a certain CSS class?

本文关键字:元素 CSS 函数 javascript 应用于 一个      更新时间:2023-09-26

我有一个导航栏,其中每个按钮改变主体的背景。他们每个人都把它变成不同的颜色。我为每个按钮创建了onmouseoveronmouseout函数来实现这一点。然而,我想知道是否有一种方法可以通过引用它们的类来编写每个函数中的一个?它们都有相同的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>

我的建议是:使用data属性并使用给定的类遍历所有元素。

function applyColor(element) {
  var color = element.getAttribute('data-bg');
  document.body.style.backgroundColor = color;
}
var buttons = document.getElementsByClassName("button");
for (var i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener("mouseover", function() {
    applyColor(this);
  }, false);
}
<nav>
  <button class="button" data-bg="red">red</button>
  <button class="button" data-bg="blue">blue</button>
  <button class="button" data-bg="yellow">yellow</button>
  <button class="button" data-bg="green">green</button>
  <button class="button" data-bg="pink">pink</button>
  <button class="button" data-bg="magenta">magenta</button>
</nav>

如前所述,getElementsByClassName返回一个集合,您不能像在jQuery中那样将事件添加到集合中。要在纯JS中做到这一点,您需要使用for循环,然后将事件附加到每个单独的元素,如下所示:

var buttons = document.getElementsByClassName('button');
for (var i = 0; i < buttons.length; i++) {
    buttons[i].onmouseover = function (event) {
        var colour = event.target.className.split(" ")[1];       
        document.body.style.backgroundColor = colour;
    }
}
http://jsfiddle.net/andyfurniss/1n5vann9/

getElementsByClassName返回一个集合。所以你必须循环遍历它,这样就可以了。

var buttons = document.getElementsByClassName('button');
[].forEach.call(buttons, function (button){
    var id = parseInt(button.id.split("").reverse().join("")); //This will give you the number from the id
    button.onmouseover = = function() {
        document.body.style.backgroundColor = whichButton(id);
    }
    button.onmouseout = function() {
        document.body.style.backgroundColor = whichButton(0);
    }
});

为了确保ES6的兼容性,有更好的方法。

var buttons = document.getElementsByClassName("button");
for (button of buttons) {
    var id = parseInt(button.id.split("").reverse().join("")); //This will give you the number from the id
    button.onmouseover = = function() {
        document.body.style.backgroundColor = whichButton(id);
    }
    button.onmouseout = function() {
        document.body.style.backgroundColor = whichButton(0);
    }
}

第一个注释实际上解决了我的问题。我这样做了:

document.onmouseover = function() {
    var x = event.target;
    y = x.id.toString().replace('button','');
    if (y > 0 && y <= 4)
        document.body.style.backgroundColor = whichButton(y);
}
document.onmouseout = function() {
    var x = event.target;
    y = x.id.toString().replace('button','');
    if (y > 0 && y <= 4)
        document.body.style.backgroundColor = whichButton(0);
}

如果我把鼠标放在一个"按钮"上,它会删除单词"按钮",留下数字(1-4),然后将其发送给我的哪个按钮函数来决定使用哪种颜色。

您可以使用事件委托,这意味着将事件侦听器附加到祖先,然后检查event.target以决定做什么。

演示:http://jsfiddle.net/a58tj1ak/

// given your HTML and whichButton function like this:
function whichButton(x) {
    var initBG = '#fff';
    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;
}
// get the buttons into an array
var buttons = [].slice.call(document.getElementsByClassName('button'));
// add event listener to the #navbar element
document.getElementById('navbar').addEventListener('mouseover', function(e){
   // target is an element being hovered
   var target = e.target;
    // check if the target is in the array of buttons
    var index = buttons.indexOf( e.target );
    if( index > -1 ){
        document.body.style.backgroundColor = whichButton(index + 1)
    }
    else {
        document.body.style.backgroundColor = whichButton(0);   
    }
});