IE7 - 设置 Javascript 生成元素的样式
这似乎很好奇,但我在 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 元素?
提前致谢
It's seems very curious but I'm having problems applying styles for javascript generated elements in IE7 but if I render the same element as string it does work.
on my 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);
this will create the script tag which I like to embed into the page, which contains:
.sample{
background: red;
}
and then for the page I'm adding a .sample
span to the body:
var sample = document.createElement('span');
sample.setAttribute('class','sample');
sample.innerHTML = 'hello there';
document.getElementsByTagName('body')[0].appendChild(sample);
When rendering on IE8/FF/Safari/Chrome, etc it renders quite well with the red background, surprisingly on IE7 it doesn't display the red background. It works if I convert the sample
element to a string and then add it to the body, but then I lost all the references being made to that element, which is no good.
so the question is: How can I apply styles correctly to the javascript elements?
thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您能否尝试将其更改
为:
正如 Andy E 在评论中提到的,在 IE 7 及更低版本中
setAttribute()
盲目地将您提供的属性映射到属性名称(例如,它映射sample .setAttribute('class', 'sample')
到sample.class = 'sample'
),因此它会破坏class
、等属性for
、onload
、onclick
等,其中 HTML 属性名称与 JavaScript 属性名称不同。Could you try changing this:
to this:
As Andy E mentioned in the comments, in IE 7 and lower
setAttribute()
blindly maps the attribute you supply to a property name (e.g. it mapssample.setAttribute('class', 'sample')
tosample.class = 'sample'
), so it breaks for attributes likeclass
,for
,onload
,onclick
, etc. where the HTML attribute name is different to the JavaScript property name.应用类时应该直接操作元素,例如:
有趣的是,你不能使用“class”这个词,因为它是 JS 中的保留词。
You should manipulate the element directly when applying classes, e.g.:
Interestingly, you can't use the word, "class", because it is a reserved word in JS.