简体   繁体   English

有没有办法用变量为 DOM 对象设置样式?

[英]Is there any way to set a style for a DOM object with a variable?

I have here some code, in which I am trying to change all of something on a page.我在这里有一些代码,我试图在其中更改页面上的所有内容。

var allElements = document.getElementsByTagName('*');

var tag = '.style.backgroundColor';
var val = 'black';

for (var i = 0; i < allElements.length;i++) {
  allElements[i] + tag = val;
}

How can I make this work?我怎样才能使这项工作?

This can be done, but not the way you are doing it.这可以做到,但不是你这样做的方式。 You'll need to pass (as an index, using bracket notation ) the CSS property name (a string) into the object returned by accessing the .style property.您需要将 CSS 属性名称(字符串)(作为索引,使用括号表示法)传递到通过访问.style属性返回的对象中。

Also, don't use .getElementsByTagName() as it's a 25+ year old API that returns a "live" node list, which can hurt performance.另外, 不要使用.getElementsByTagName()因为它是一个 25 年以上的 API,它返回一个“实时”节点列表,这可能会影响性能。 Instead, use .querySelectorAll() and loop over the returned collection with the Array.forEach() method, which is an alternative to a traditional for counting loop that is a bit easier to work with since you don't have to manage any loop counters and get direct access to the element you are iterating.相反,使用.querySelectorAll()和遍历返回的集合与Array.forEach()方法,这是一种替代传统的for计数循环是一个容易一点工作以来你没有管理任何环计数器并直接访问您正在迭代的元素。

 var allElements = document.querySelectorAll('*'); var tag = 'backgroundColor'; // Just store the name of the CSS property var val = 'black'; // Use the more modern Array.forEach() method of looping allElements.forEach(function(element){ element.style[tag] = val; // Pass the style object's property name as an index });
 * { color:white; border:2px solid white; }
 <div>This is a div<br>that spans two lines.<div> <p>Here's a paragraph</p> <h1>And a Heading 1</h1>

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

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