使用纯 javascript 设置样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42942002/
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
Set style using pure javascript
提问by Giala Jefferson
I want to set body's background without jquery.
我想在没有 jquery 的情况下设置 body 的背景。
jquery : $('body').css('background','red');
jquery : $('body').css('background','red');
Why this won't work in pure JS?
为什么这在纯 JS 中不起作用?
document.getElementsByTagName('body').style['background'] = 'red';
document.getElementsByTagName('body').style['background'] = 'red';
回答by Chinito
var obj = document.getElementsByTagName('div')[0].style.backgroundColor = 'RED';
<div>sample</div>
回答by Srikrushna
There are many ways you can set the background color. But getElementsByTagNamedoes not return a single object, it's a collection of objects
您可以通过多种方式设置背景颜色。但是getElementsByTagName不返回单个对象,它是对象的集合
document.body.style.backgroundColor = "green"; //javascript
document.getElementsByTagName("body")[0].style.backgroundColor = "green"; //another one
回答by Sagar V
getElementsByTagNamenot return a single element instad a collection.
getElementsByTagName在集合中不返回单个元素。
Try this
尝试这个
document.getElementsByTagName('body')[0].style.backgroundColor = 'red';

