我这里有一些代码,我试图在其中更改页面上的所有内容。
var allElements = document.getElementsByTagName('*');
var tag = '.style.backgroundColor';
var val = 'black';
for (var i = 0; i < allElements.length;i++) {
allElements[i] + tag = val;
}
我怎样才能做到这一点?
最佳答案
这是可以做到的,但不是你这样做的方式。您需要将 CSS 属性名称(字符串)传递(作为索引,使用 bracket notation )到通过访问 .style
属性返回的对象中。
此外,don't use .getElementsByTagName()
因为它是一个已有 25 多年历史的 API,它返回“实时”节点列表,这可能会损害性能。相反,使用 .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>
关于javascript - 有什么方法可以为带有变量的 DOM 对象设置样式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59294452/