简体   繁体   English

使用 Javascript 更改文本颜色?

[英]Change text color with Javascript?

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...这是我的代码,但它不起作用,我不知道为什么不......

 var about; function init() { about = document.getElementById("about").innerHTML; about.style.color = 'blue'; }
 <div id="about">About Snakelane</div> <input type="image" src="http://www.blakechris.com/snakelane/assets/about.png" onclick="init()" id="btn">

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.使用innerHTML您可以获取/设置元素的内容。 So if you would want to modify your title, innerHTML would be the way to go.所以如果你想修改你的标题, 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属性。

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演示

Try below code:试试下面的代码:

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

http://jsfiddle.net/jPCFC/ http://jsfiddle.net/jPCFC/

innerHTML is a string representing the contents of the element. innerHTML是一个表示元素内容的字符串。

You want to modify the element itself.您想修改元素本身。 Drop the .innerHTML part.删除.innerHTML部分。

<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';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM