javascript 如何使用javascript设置H1的颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14053390/
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
How to set the color of H1 using javascript?
提问by sdnr1
I wanted to know that how can i set the color of the text enclosed in H1 tag using javascript. For this i cant use css.
我想知道如何使用 javascript 设置包含在 H1 标签中的文本的颜色。为此,我不能使用 css。
The script i tried was this-
我试过的剧本是这样的——
document.h1.style.color="#fff"
But this doesnt work. Pls help.
但这不起作用。请帮忙。
EDIT-
编辑-
I really couldnt find anything suitabble to this. Actually i do not know much about javascript and have encounter a problem where i have to use javascript to set the color of H1.
我真的找不到任何适合这个的东西。其实我不太了解javascript并且遇到了一个问题,我必须使用javascript来设置H1的颜色。
Now how can i do the same thing but with the p tag.
现在我怎么能做同样的事情,但用 p 标签。
回答by asgoth
var h1Elements = document.getElementsByTagName("h1");
for(var i = 0; i < h1Elements.length; i++) {
h1Elements[i].style.color = "#fff";
}
回答by Nick.T
You need to get the element. Lookup something like this :
您需要获取元素。查找类似这样的内容:
document.getElementsByTagName('H1')[0]
then you just fiddle about with the attributes and styles.
然后你只需摆弄属性和样式。
回答by ameya rote
Please copy this code into any editor..Enjoy.
请将此代码复制到任何编辑器中..享受。
<!DOCTYPE html>
<html>
<body>
<h1 id="h1">The content</h1> <h1>of the body</h1> element is displayed in your browser.
</br></br></br>
<div onclick="checkAll()"> Click me To See Change</div>
</body>
<script>
function checkAll() {
var divs = document.getElementsByTagName("h1"); // Access all <H1> present in your body.
for(var i = 0; i < divs.length; i++) { //divs.length contain number of <h1> elements
var div = divs[i]; // Now access Each <H1> one-by-one
div.style.color = 'green'; // Set Color Style of each <h1>
}
}
</script>
</html>
回答by Klevis Miho
You can do it very easily with jQuery:
你可以很容易地用 jQuery 做到这一点:
$('h1').css({'color' : '#fff'});