使用javascript控制css与Mozilla& Chrome但不是IE浏览器

时间:2010-04-25 22:50:28

标签: javascript internet-explorer google-chrome webkit

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

the code:

/*! 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);

}/*___________________________________________________________________________*/

the use of the function:

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

5 个答案:

答案 0 :(得分:3)

var style = document.createElement('style');

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

style.rel = 'stylesheet';
style.href = 'FireFox.css';

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

var link= document.createElement('link');
link.rel= 'stylesheet';
link.href= 'something.css';
head.appendChild(link);

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

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

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);

答案 1 :(得分:3)

已经过测试,适用于所有主流浏览器(Chrome / Safari / FF / Opera / IE),包括IE6,7 + 8:

function createCSS(css, doc) {
    doc = doc || document;
    var style = doc.createElement("style");
    style.type = "text/css";

    if (!window.opera && 'styleSheet' in style && 'cssText' in style.styleSheet) {
        // Internet Explorer 6-8 don't support adding text nodes to 
        // styles, so use the proprietary `styleSheet.cssText` instead
        style.styleSheet.cssText = css;
    }
    else {
        // Otherwise use the standard method
        style.appendChild(doc.createTextNode(css));
    }

    // Note the `|| document.body` as getting the
    // head doesn't always work on e.g. Safari 1.0
    var head = doc.getElementsByTagName("head")[0] || doc.body;

    // Add the new style of higher priority than the last
    // ones if there's already other elements in the head
    if (head.firstChild) {
        head.insertBefore(style, head.firstChild);
    }
    else {
        head.appendChild(style);
    }
}

编写代码时,它与所服务的文档有关,因此可能需要修改以使其相对于另一个路径,或者您可以在CSS中使用绝对图像路径。

编辑:删除了所有innerHTML引用,以便在可能的情况下使用更标准的createTextNode并清理各种内容。

答案 2 :(得分:2)

我知道这是一个旧线程,但我正在寻找一种动态插入CSS样式的解决方案,适用于所有常见/主流浏览器。我想和你分享我的解决方案。大卫的解决方案效果不好(抱歉)。我已经制作了一个工具提示javascript / jQuery类,可以使用内联样式,但也可以使用CSS样式的样式。 (offtopic:该类也可以自动对齐工具提示,如默认工具提示)。

也许您想知道插入CSS时的好处是什么,如上例所示。好吧,你不需要一个带有样式的额外CSS文件,你可以动态地从脚本添加样式,当你处理图像时,你可以动态地改变图像的路径(所以你不需要改变任何文件)。您还可以在其他样式表/样式规则中插入样式,并且可以在下面的其他样式表中修改应用样式规则(当您使用内联样式或将插入的规则置于任何现有样式表之下时,这是不可能的。)

此功能适用于 Opera / Firefox / IE7 / IE8 / IE9 / Chrome / Safari (未经任何黑客攻击!):

    function addHtmlStyles( sCss, oBefore ) 
    {
     var oHead = document.getElementsByTagName('head')[0];
     if( !oHead || oHead == null ) 
      { return false; }

     var bResult = false,
         oStyle = document.createElement('style');
     oStyle.type = 'text/css';
     oStyle.rel = 'stylesheet';
     oStyle.media = 'screen';

     if( typeof oStyle.styleSheet == 'object' ) 
      {  // IE route (and opera)
        try{ oStyle.styleSheet.cssText = sCss; bResult = true; }
        catch(e) {}  
      }
     else { 
             // Mozilla route
            try{ oStyle.innerHTML = sCss; bResult = true; }
            catch(e) {};
            if( !bResult )
            {
               // Webkit route
              try{ oStyle.innerText = sCss; bResult = true; }
              catch(e) {};
            }
          }

     if( bResult )
     {
      try 
      {
      if( typeof oBefore == 'object' )
       { oHead.insertBefore(oStyle, oBefore ); }
      else { oHead.appendChild(oStyle); }
      }
      catch(e) { bResult = false; }
     }

 return bResult;
}

正确时返回true,失败时返回false。例如:

var sCss = '#tooltip {background:"#FF0000";}';

// get first stylesheet with jQuery, we don't use $('head') because it not always working
// If there is no stylesheet available, it will be added at the end of the head tag.
var oHead = $(document.getElementsByTagName('head')[0]),
    oFirst = oHead.find('[rel=stylesheet]').get(0);

if( addHtmlStyles( sCss, oFirst ))
 { alert( 'OK' ); }
else { alert( 'NOT OK' ); }

这就是全部。希望你喜欢这个解决方案。 格尔茨, Erwin Haantjes

答案 3 :(得分:1)

@GlassGost:很奇怪不适合你,因为我在几个浏览器中测试它(也在移动浏览器上)。也许在DOM准备就绪时添加css会有所帮助:

$(document).ready( function()
{
  .......
});

有时也有助于更改加载脚本的顺序。

格尔茨, Erwin Haantjes

答案 4 :(得分:0)

对于我所有当前具有任何类型文档的浏览器(我假设您必须处理多个文档,否则您将没有Doc参数),这对我来说很好用:

function add_css_style(css_rules, document) {
    document = document || self.document;
    var style = document.createElementNS("http://www.w3.org/1999/xhtml", "style");
    style.type = "text/css";
    style.appendChild(document.createTextNode(css_rules));
    document.documentElement.appendChild(style);
}

如果您想改用CSSOM:

function add_css_style(css_rules, document) {
    document = document || self.document;
    var stylesheet = document.documentElement.appendChild(
        this.createElementNS("http://www.w3.org/1999/xhtml", "style")
    ).sheet;
    stylesheet.insertRule("@media all{" + rules + "}", 0);
}