document.write 样式 css javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13259915/
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
document.write style css javascript
提问by user1689274
I'm pulling a bit of html and css from a database, and it happens to contain a bit of css wrapped in a style tag. I then set some innerhtml to the string variable and display it.
我从数据库中提取了一些 html 和 css,它恰好包含一些包裹在样式标签中的 css。然后我将一些innerhtml 设置为字符串变量并显示它。
The html is rendered properly, but ie will not display the content with the css - of course firefox will. Below is an abbreviated example of the code
html 正确呈现,但 ie 不会显示带有 css 的内容 - 当然 firefox 会。下面是代码的缩写示例
var outputString = '<style type="text/css">.fontRed{color:red;}</style><span class="fontRed">red</span>'
I then set it to the innerHTML
然后我将它设置为innerHTML
document.getElementById('bilbo').innerHTML = outputString;
This displays properly (the color red) in FF, however does not in IE. Is there a character I need to escape for IE? The rest of the html works, and even inline styles work correctly in IE.
这在 FF 中正确显示(红色),但在 IE 中不显示。是否有我需要为 IE 转义的字符?其余的 html 有效,甚至内联样式在 IE 中也能正常工作。
Any assistance would be most welcome.
任何帮助将是最受欢迎的。
Thanks
谢谢
采纳答案by Alohci
Just put <body>
at the start of the output string. i.e.
只需放在<body>
输出字符串的开头即可。IE
document.getElementById('bilbo').innerHTML = '<body>' + outputString;
See http://jsfiddle.net/ScEZ4/1/for a working demo.
有关工作演示,请参阅http://jsfiddle.net/ScEZ4/1/。
Tested and working IE6, IE7, IE8, IE9, FF16, Chrome22, Opera12
经测试可运行 IE6、IE7、IE8、IE9、FF16、Chrome22、Opera12
回答by Sushanth --
Try this Approach .. Tested in IE7 and above
试试这个方法 .. 在 IE7 及更高版本中测试
// Create the Style Element
var styleElem = document.createElement('style');
styleElem.type = 'text/css' ;
var css = '.fontRed{color:red;}' ;
if(styleElem.styleSheet){
styleElem.styleSheet.cssText = css;
}
else{
styleElem.appendChild(document.createTextNode(css));
}
// Append the Style element to the Head
var head = document.getElementsByTagName('head')[0] ;
head.appendChild(styleElem);
// Append the span to the Div
var container = document.getElementById('bilbo');
container.innerHTML = '<span class="fontRed">red</span>' ;?
回答by Jules
Append the <style type="text/css">.fontRed{color:red;}</style>
to the head tag first.
首先将 附加<style type="text/css">.fontRed{color:red;}</style>
到 head 标签。