0

我正在尝试创建一个文档片段并为其设置样式,但是遇到了很多困难。讽刺的是,IE 不是我的问题!

我有这个:

var newDom = document.createDocumentFragment();

newDom.appendChild(document.createElement("style"));
newDom.appendChild(document.createElement("div"));

if (newDom.childNodes[0].styleSheet){
    newDom.childNodes[0].styleSheet.cssText = "div{color:red;}";
    alert(newDom.childNodes[1].currentStyle.color);
}else{
    newDom.childNodes[0].appendChild(document.createTextNode("div{color:red;}"));
    alert(window.getComputedStyle(newDom.childNodes[1], null).color);
};

...在 IE7/8/9 中提示“红色”,但在 FF3.0/4/10 中提示“rgb(0,0,0)”。而且,是的,我需要知道应用了哪些样式,所以我需要从 FF 中的 getComputedStyle 中读取(或使用其他方法,只要它是可靠的)。

我究竟做错了什么?这可能吗?(我想/希望如此......)

我尝试了很多东西——比如“newDom.styleSheets”,它存在于 IE 中但不存在于 FF 中——但无济于事。

请帮忙 - 谢谢!:D

4

1 回答 1

2

在网上阅读,似乎使用 Javascript 更改 CSS 的正确语法是:

obj.style.cssText = 'something';

无论如何,这似乎并不能解决问题。我建议您阅读这篇文章,这可能会对您有所帮助:http ://www.phpied.com/the-new-game-show-will-it-reflow/ 。

我还建议更改方法并将您的 CSS 代码放在预先存在的 CSS 样式表中.red-color,与setAttribute('class', 'red-color'). 另一种选择是设置内联样式,始终使用相同的功能:setAttribute('style', 'color: red').

于 2012-02-03T20:07:46.237 回答