javascript 使用 document.getElementById("id").innerHTML 时如何更改文本颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31719391/
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-28 14:15:43  来源:igfitidea点击:

How to change colour of text when using document.getElementById("id").innerHTML

javascripthtmlinnerhtml

提问by TheLuminor

I am trying to change the text of a span to something else when a particular event occurs. I am doing this as :

当特定事件发生时,我试图将跨度的文本更改为其他内容。我这样做:

document.getElementById("usernameError").innerHTML = "**Message";

I want to display the same in a different colour. Any idea on how to do that? Much appreciated!

我想以不同的颜色显示相同的内容。关于如何做到这一点的任何想法?非常感激!

采纳答案by Eric Bulloch

You could always just put the message in a span and put a style attribute on it. This should do it:

您总是可以将消息放在一个跨度中并在其上放置一个样式属性。这应该这样做:

document.getElementById("usernameError").innerHTML = "<span style='color: red;'>**Message</span>";

回答by Eloy Pineda

As you can find in the Mozilla Developer Network, you can use HTMLElement.styleproperty to change any style on the element.

正如您在Mozilla 开发人员网络所见,您可以使用HTMLElement.style属性来更改元素上的任何样式。

So you can do something like this to colour it in red:

因此,您可以执行以下操作将其着色为红色:

 document.getElementById("usernameError").style.color = '#d00'

回答by EaziLuizi

A more future proof and reusable solution would probably be to add a class to either the current element or the span element, depending on your requirements:

一个更具未来证明和可重用的解决方案可能是向当前元素或 span 元素添加一个类,具体取决于您的要求:

document.getElementById("usernameError").className = "color-red";

Or working off Erics solution:

或者使用 Eric 解决方案:

document.getElementById("usernameError").innerHTML = "<span class='color-red'>**Message</span>";

Then in your CSS:

然后在你的 CSS 中:

.color-red{
    color: #F00;
}

You could obviously also add diff colours and attribute in a much more maintainable way like this.

显然,您也可以像这样以更易于维护的方式添加差异颜色和属性。

NOTE: classNameReturns A String, representing the class, or a space-separated list of classes, of an element.

注意:className返回一个字符串,表示元素的类或以空格分隔的类列表。