[英]DOM Javascript on Internet Explorer 8
我在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);
}
您可以通过使用
document.createStyleSheet
。 在google doctype Wiki上,它显示了如何使用它们的库在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;
}
};
Quirksmode.org断言 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;
}
无论我将脚本放在头部,段落之前的正文中还是段落之后的正文中,它都同样有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.