使用 Javascript 更改文本颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17925577/
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
Change text color with Javascript?
提问by Sirko
I want to change the color of a title when a button is clicked. This is my code, but it's not working and I can't figure out why not...
我想在单击按钮时更改标题的颜色。这是我的代码,但它不起作用,我不知道为什么不......
<div id="about">About Snakelane</div>
<input type="image" src="http://www.blakechris.com/snakelane/assets/about.png" onclick="init()" id="btn">
and my js...
还有我的js...
var about;
function init() {
about = document.getElementById("about").innerHTML;
about.style.color = 'blue';
}
Thanks in advance!
提前致谢!
回答by Sirko
You set the style per element and not by its content:
您设置每个元素的样式而不是其内容:
function init() {
document.getElementById("about").style.color = 'blue';
}
With innerHTML
you get/set the content of an element. So if you would want to modify your title, innerHTML
would be the way to go.
随着innerHTML
您获取/设置元素的内容。所以如果你想修改你的标题,innerHTML
这就是要走的路。
In your case, however, you just want to modify a property of the element (change the color of the text inside it), so you address the style
property of the element itself.
但是,在您的情况下,您只想修改元素的属性(更改其中文本的颜色),因此您可以解决style
元素本身的属性。
回答by Dhaval Marthak
回答by Nitin Chaurasia
Try below code:
试试下面的代码:
$(document).ready(function(){
$('#about').css({'background-color':'black'});
});
回答by Nipu
<div id="about">About Snakelane</div>
<input type="image" src="http://www.blakechris.com/snakelane/assets/about.png" onclick="init()" id="btn">
<script>
var about;
function init() {
about = document.getElementById("about");
about.style.color = 'blue';
}
回答by Quentin
innerHTML
is a string representing the contents of the element.
innerHTML
是表示元素内容的字符串。
You want to modify the element itself. Drop the .innerHTML
part.
您想修改元素本身。放下.innerHTML
零件。