使用querySelectorAll来更改多个元素的样式属性 [英] Using querySelectorAll to change the style property of multiple elements

查看:4969
本文介绍了使用querySelectorAll来更改多个元素的样式属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

然而我希望这个函数同时适用于多个DIV。我尝试给每个DIV使用相同的类名,然后使用 getElementsByClassName 但无法弄清楚如何实现它。



< querySelectorAll 会更合适,如果是的话,我将如何实现它?

解决方案

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

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






编辑:正如上面的评论所说,你可能会更好如果它们不是动态的并且使用,请将这些值放在类中:

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


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

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 getElementsByClassName but couldn't figure out how to implement it.

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

解决方案

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

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');

这篇关于使用querySelectorAll来更改多个元素的样式属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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