在 Javascript .innerHTML 中使用 CSS 样式表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28458208/
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
Using a CSS Stylesheet with Javascript .innerHTML
提问by Hyman Parker
If I have a javascript function that loads an error using
如果我有一个使用加载错误的 javascript 函数
document.getElementById("ID").innerHTML = "This is your error";
And I want to stylize it say change the text to a different color, and put the error into a different position, how would I go about doing that? I've been looking around, and cannot find any information.
我想风格化它说将文本更改为不同的颜色,并将错误放在不同的位置,我该怎么做?我一直在环顾四周,没有找到任何信息。
回答by Dieterg
As innerHTML suggests you can also add HTML. You could for instance add a span tag with a class that you style via CSS.
正如innerHTML 建议的那样,您还可以添加HTML。例如,您可以使用通过 CSS 设置样式的类添加 span 标签。
JS/CSS and HTML
JS/CSS 和 HTML
document.getElementById('error-message').innerHTML = "<span class='error'>my error</span>";
.error {
color: red;
font-size: 24px;
}
<div id="error-message"></div>
回答by Mohit Bhasi
Check this out , this answer should suffice to your needs:
看看这个,这个答案应该足以满足您的需求:
document.getElementById("ID").innerHTML = "This is your error";
var sheet = document.createElement('style')
sheet.innerHTML = "div {color:red;overflow:hidden;}";
document.body.appendChild(sheet);
Add the below line to your span
将以下行添加到您的跨度
#myspan{float:left;}
Working fiddle:http://jsfiddle.net/0z971bsn/
工作小提琴:http: //jsfiddle.net/0z971bsn/
As you mentioned in the comments , to check for errors you can refer to the answer to this question How to get my forms' Javascript error function to cancel form submission and insert error message?
正如您在评论中提到的,要检查错误,您可以参考这个问题的答案如何获取我的表单的 Javascript 错误功能以取消表单提交并插入错误消息?

