我从数据库中提取了一些 html 和 css,它恰好包含一些包裹在样式标签中的 css。然后我将一些 insidehtml 设置为字符串变量并显示它。
html 已正确呈现,但 ie 不会显示带有 css 的内容 - 当然 firefox 会。下面是代码的缩写示例
var outputString = '<style type="text/css">.fontRed{color:red;}</style><span class="fontRed">red</span>'
然后我将其设置为innerHTML
document.getElementById('bilbo').innerHTML = outputString;
这在 FF 中可以正确显示(红色),但在 IE 中却不能。 我需要为 IE 转义某个字符吗? html 的其余部分可以正常工作,甚至内联样式在 IE 中也可以正常工作。
非常欢迎任何帮助。
谢谢
最佳答案
尝试此方法..在 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>' ;
<强> Check FIDDLE
关于javascript - document.write 样式 css javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13259915/