使用javascript控制css适用于Mozilla和Chrome但不适用于IE

Gla*_*ost 6 javascript internet-explorer webkit google-chrome

我在使用与Internet Explorer一起使用css(使用文本变量)的函数时遇到了问题,但它适用于Firefox和Chrome.

代码:

/*! addCssStyle() applies the text value $CssText$ to the the specified document
$Doc$ e.g. an IFrame; or if none specified, default to the current document,
*/function addCssStyle(CssText, Doc){

//Secure $Head$ for the current $Doc$
    Doc = Doc||document;    var head = Doc.getElementsByTagName('head')[0];
    if(!head || head == null){
        head = Doc.createElement('div');    Doc.body.appendChild(head);
    } if(!head || head == null){return false;}

//createElement('style')
    var PendingStyle = Doc.createElement('style');
//  if (is_gecko){PendingStyle.href = 'FireFox.css';}//???needeed???
    PendingStyle.type = 'text/css';
    PendingStyle.rel = 'stylesheet';
//  PendingStyle.media = 'screen';//???needeed???
    PendingStyle.innerHTML = CssText;
    head.appendChild(PendingStyle);

}/*___________________________________________________________________________*/
Run Code Online (Sandbox Code Playgroud)

使用功能:

var NewSyleText = //The page styling
"h1, h2, h3, h4, h5 {font-family: 'Verdana','Helvetica',sans-serif; font-style: normal; font-weight:normal;}" +
"body, b {background: #fbfbfb; font-style: normal; font-family: 'Cochin','GaramondNo8','Garamond','Big Caslon','Georgia','Times',serif;font-size: 11pt;}" +
"p { margin: 0pt; text-indent:2.5em;  margin-top: 0.3em; }" +
"a {    text-decoration: none; color: Navy; background: none;}" +
"a:visited {    color: #500050;}" +
"a:active { color: #faa700;}" +
"a:hover {  text-decoration: underline;}";
addCssStyle(NewSyleText);//inserts the page styling
Run Code Online (Sandbox Code Playgroud)

bob*_*nce 3

var style = document.createElement('style');
Run Code Online (Sandbox Code Playgroud)

通过使用 DOM 方法创建元素来添加新的样式表和脚本一直是跨浏览器的冒险行为。这在 IE 或 WebKit 中不起作用。

style.rel = 'stylesheet';
style.href = 'FireFox.css';
Run Code Online (Sandbox Code Playgroud)

HTMLStyleElement 上没有此类属性。<style>包含内联代码。对于外部样式表,请使用<link>. 幸运的是,这确实有效:

var link= document.createElement('link');
link.rel= 'stylesheet';
link.href= 'something.css';
head.appendChild(link);
Run Code Online (Sandbox Code Playgroud)

但并没有为您提供从脚本插入规则的便捷方法。

您还可以使用该界面将新规则添加到现有样式表(例如style中的空样式表) 。不幸的是,IE 的界面不太符合这里的标准,所以你需要代码分支:<head>document.styleSheets

var style= document.styleSheets[0];
if ('insertRule' in style)
    style.insertRule('p { margin: 0; }', 0);
else if ('addRule' in style)
    style.addRule('p', 'margin: 0', 0);
Run Code Online (Sandbox Code Playgroud)