简体   繁体   English

在多个HTML元素上设置CSS属性

[英]Set CSS properties on multiple HTML elements

I have this part of a function that sets css properties on two buttons (update, save). 我有这部分功能,可以在两个按钮(更新,保存)上设置css属性。 I'm trying to minimize the lines of code and i'm looking for a more efficient way of setting css properties on multiple HTML elements rather than writing getElementById for every element. 我正在尝试最小化代码行,并且我正在寻找一种更有效的方法来在多个HTML元素上设置css属性,而不是为每个元素编写getElementById。 Is querySelectorAll suitable for use in this context? querySelectorAll是否适合在此上下文中使用?

//Chris //克里斯

var css = {"backgroundColor": "red","textDecoration": "line-through"};
  for (var prop in css) {   
    document.getElementById("update").style[prop] = css[prop];
    document.getElementById("save").style[prop] = css[prop];
  }

I'd suggest the following method 我建议以下方法

var css = {"backgroundColor": "red","textDecoration": "line-through"};
var elements = document.querySelectorAll('#update, #save');
for (var prop in css) {
    elements.forEach(function (element) {
        element.style[prop] = css[prop];
    });
}

here the querySelectorAll is used with multiple selectors 这里的querySelectorAll与多个选择器一起使用

Yes, querySelectorAll could be used in this context. 是的,可以在此上下文中使用querySelectorAll Be aware that it isn't supported in IE8 or earlier. 请注意,IE8或更早版本不支持它。 Check out the MSN docs for some quirks . 查看MSN文档中的一些怪癖

In addition, be aware that querySelectorAll returns an array like object (a non live NodeList) so you'll have to modify your code to work with such a structure: 另外,请注意querySelectorAll返回一个类似于object的数组(非活动NodeList),因此您必须修改代码以使用这种结构:

var css = {"backgroundColor": "red","textDecoration": "line-through"}; 

var matched = document.querySelectorAll("#update, #save");
matched.forEach(function (c){
  c.style.backgroundColor css.backgroundColor;
  c.style.textDecoration = css.textDecoration;
});

Using document.querySelectorAll you could do it this way. 使用document.querySelectorAll您可以通过这种方式做到这一点。

/*declare a css class*/

.button-css{"backgroundColor": "red","textDecoration": "line-through"};

/*in javascript you can do the following*/
var buttons=document.querySelectorAll(".buttons");

buttons.forEach(function(button){
  button.classList.add('button-css');
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM