使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:07:31  来源:igfitidea点击:

Change text color with Javascript?

javascriptbuttoncolorsonclick

提问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 innerHTMLyou get/set the content of an element. So if you would want to modify your title, innerHTMLwould 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 styleproperty of the element itself.

但是,在您的情况下,您只想修改元素的属性(更改其中文本的颜色),因此您可以解决style元素本身的属性。

回答by Dhaval Marthak

use ONLY

仅使用

function init() { 
    about = document.getElementById("about");
    about.style.color = 'blue';
}

.innerHTML()sets or gets the HTML syntax describing the element's descendants., All you need is an object here.

.innerHTML()设置或获取描述元素后代的 HTML 语法。, 在这里你只需要一个对象。

Demo

演示

回答by Nitin Chaurasia

Try below code:

试试下面的代码:

$(document).ready(function(){
$('#about').css({'background-color':'black'});    
});

http://jsfiddle.net/jPCFC/

http://jsfiddle.net/jPCFC/

回答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

innerHTMLis a string representing the contents of the element.

innerHTML是表示元素内容的字符串。

You want to modify the element itself. Drop the .innerHTMLpart.

您想修改元素本身。放下.innerHTML零件。