Javascript 使用 querySelectorAll 改变多个元素的样式属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33178114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:44:22  来源:igfitidea点击:

Using querySelectorAll to change the style property of multiple elements

javascripthtmlcss

提问by user2840467

I have the following function which when triggered will make a DIV become semi-transparent.

我有以下功能,触发时会使 DIV 变为半透明。

function changeOpacity(el) {
    var elem = document.getElementById(el);
    elem.style.transition = "opacity 0.5s linear 0s";
    elem.style.opacity = 0.5;
}

However I would like this function to apply to several DIVs simultaneously. I tried giving each DIV the same class name and then using getElementsByClassNamebut couldn't figure out how to implement it.

但是,我希望此功能同时应用于多个 DIV。我尝试为每个 DIV 赋予相同的类名,然后使用getElementsByClassName但无法弄清楚如何实现它。

Would querySelectorAllbe more appropriate and if so how would I implement it?

querySelectorAll更合适,如果是这样,我将如何实施它?

回答by AtheistP3ace

I would select them with a querySelectorAll and loop over them.

我会用 querySelectorAll 选择它们并循环它们。

function changeOpacity(className) {
    var elems = document.querySelectorAll(className);
    var index = 0, length = elems.length;
    for ( ; index < length; index++) {
        elems[index].style.transition = "opacity 0.5s linear 0s";
        elems[index].style.opacity = 0.5;
    }
}

Edit: As a comment said above you might be better off putting these values in a class if they are not dynamic and use:

编辑:正如上面的评论所说,如果这些值不是动态的并且使用,则最好将它们放在一个类中:

elems[index].classList.add('someclass');

回答by Allen

Another way this can be done is with forEach()and ES6+

另一种方法是使用forEach()和 ES6+

function changeOpacity(className) {
    document.querySelectorAll(className).forEach(el => {
        el.style.transition = "opacity 0.5s linear 0s";
        el.style.opacity = 0.5;
    });
}

I especially like this syntax when only one style property needs to be updated. For example, if you only needed to change the opacity, and not the transition, you could use a single line:

当只需要更新一个样式属性时,我特别喜欢这种语法。例如,如果您只需要更改不透明度,而不需要更改过渡,则可以使用一行:

function setOpacity(className) {
    document.querySelectorAll(className).forEach(el => el.style.opacity = 0.5);
}

You could then use a separate method for setting the transition:

然后,您可以使用单独的方法来设置过渡:

function setTransition(className) {
   document.querySelectorAll(className).forEach(
       el => el.style.transition = "opacity 0.5s linear 0s";
   });
}