【问题标题】:DOM Javascript on Internet Explorer 8Internet Explorer 8 上的 DOM Javascript
【发布时间】:2011-04-06 16:35:16
【问题描述】:
我对 Internet Explorer 中的 CSS 修改有一点问题。当我在<head> 中添加新的 CSS 样式时,IE 不会重新加载注入新 CSS 的页面。但是当我改变一个元素的 CSS 属性时,它就起作用了!此代码在 Firefox 上完美运行,所以我不明白为什么它在 IE 中不起作用。
你对头部修改工作有什么想法吗?
if(document.createStyleSheet) {
document.createStyleSheet('http://www.xxxx.com/style.css');
} else {
newnode=document.createElement('link');
newnode.id='newStyle';
newnode.media="all";
newnode.rel="stylesheet";
newnode.type="text/css";
newnode.href='http://www.xxxx.com/style.css';
document.getElementsByTagName('head')[0].readOnly=false;
document.getElementsByTagName('head')[0].appendChild(newnode);
}
【问题讨论】:
标签:
javascript
html
internet-explorer
dom
【解决方案1】:
Quirksmode.org asserts 说createStyleSheet() 方法是IE 独有的,符合我的经验。以下代码适用于 IE 9,但不适用于 FF 4、Chrome 11 或 Safari 5。
<html>
<head>
<script type="text/javascript">
if(document.createStyleSheet())
{
document.createStyleSheet("external.css");
}
</script>
</head>
<body>
<p id="important">This is an important paragraph.</p>
</body>
</html>
其中 external.css 包含以下规则:
#important
{
font-family: Arial;
}
无论我将脚本放在头部、段落之前的正文中还是段落之后的正文中,它的效果都一样好。
【解决方案2】:
你可以使用
document.createStyleSheet
。在google doctype wiki 上,它显示了如何使用他们的library 在 IE 中为您添加样式:
/**
* Installs the styles string into the window that contains opt_element. If
* opt_element is null, the main window is used.
* @param {String} stylesString The style string to install.
* @param {Element} opt_element Element who's parent document should have the
* styles installed.
* @return {Element} The style element created.
*/
goog.style.installStyles = function(stylesString, opt_element) {
var dh = goog.dom.getDomHelper(opt_element);
var styleSheet = null;
if (goog.userAgent.IE) {
styleSheet = dh.getDocument().createStyleSheet();
} else {
var head = dh.$$('head')[0];
// In opera documents are not guaranteed to have a head element, thus we
// have to make sure one exists before using it.
if (!head) {
var body = dh.$$('body')[0];
head = dh.createDom('head');
body.parentNode.insertBefore(head, body);
}
styleSheet = dh.createDom('style');
dh.appendChild(head, styleSheet);
}
goog.style.setStyles(styleSheet, stylesString);
return styleSheet;
};
/**
* Sets the content of a style element. The style element can be any valid
* style element. This element will have its content completely replaced by
* the new stylesString.
* @param {Element} element A stylesheet element as returned by installStyles
* @param {String} stylesString The new content of the stylesheet
*/
goog.style.setStyles = function(element, stylesString) {
if (goog.userAgent.IE) {
// Adding the selectors individually caused the browser to hang if the
// selector was invalid or there were CSS comments. Setting the cssText of
// the style node works fine and ignores CSS that IE doesn't understand
element.cssText = stylesString;
} else {
var propToSet = goog.userAgent.SAFARI ? 'innerText' : 'innerHTML';
element[propToSet] = stylesString;
}
};