这似乎很好奇,但我在 IE7 中为 javascript 生成的元素应用样式时遇到问题,但如果我将相同的元素渲染为字符串,它确实可以工作。
在我的 JavaScript 上:
var style = document.createElement('link');
style.setAttribute('type','text/css');
style.setAttribute('rel', 'stylesheet');
style.setAttribute('href', url('assets/default.css'));
document.getElementsByTagName('head')[0].appendChild(style);
这将创建我喜欢嵌入到页面中的脚本标记,其中包含:
.sample{
background: red;
}
然后对于页面,我将 .sample
范围添加到正文:
var sample = document.createElement('span');
sample.setAttribute('class','sample');
sample.innerHTML = 'hello there';
document.getElementsByTagName('body')[0].appendChild(sample);
在 IE8/FF/Safari/Chrome 等上渲染时,它在红色背景下渲染得很好,令人惊讶的是在 IE7 上它不显示红色背景。如果我将 sample
元素转换为字符串,然后将其添加到正文中,它会起作用,但随后我会丢失对该元素的所有引用,这不好。
所以问题是:如何正确地将样式应用于 javascript 元素?
提前致谢
最佳答案
您可以尝试更改此设置吗:
sample.setAttribute('class','sample');
对此:
sample.className = 'sample';
正如 Andy E 在评论中提到的,在 IE 7 及更低版本中 setAttribute()
盲目地将您提供的属性映射到属性名称(例如,它映射 sample.setAttribute('class' , 'sample')
到 sample.class = 'sample'
),因此对于 class
、for
、 onload
、onclick
等,其中 HTML 属性名称与 JavaScript 属性名称不同。
关于javascript - IE7 - 设置 Javascript 生成元素的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3520970/