使用 Javascript 更改文本颜色? [英] Change text color with Javascript?

查看:31
本文介绍了使用 Javascript 更改文本颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在单击按钮时更改标题的颜色.这是我的代码,但它不起作用,我不知道为什么不...

var about;函数初始化(){about = document.getElementById("about").innerHTML;about.style.color = '蓝色';}

<div id="about">关于Snakelane</div><input type="image" src="http://www.blakechris.com/snakelane/assets/about.png" onclick="init()" id="btn">

解决方案

你设置每个元素的样式,而不是它的内容:

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

使用 innerHTML 获取/设置元素的内容.因此,如果您想修改标题,innerHTML 将是您的最佳选择.

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

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. So if you would want to modify your title, innerHTML would be the way to go.

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.

这篇关于使用 Javascript 更改文本颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆