DOM Javascript в Internet Explorer 8 - PullRequest
       0

DOM Javascript в Internet Explorer 8

0 голосов
/ 01 сентября 2010

У меня небольшая проблема с модификациями CSS в Internet Explorer. Когда я добавляю новый стиль CSS в <head>, 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);
}

Ответы [ 2 ]

0 голосов
/ 19 мая 2011

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

И это работало одинаково хорошо везде, где я помещал сценарий, в голову, в тело перед абзацем или в теле после абзаца.

0 голосов
/ 01 декабря 2010

Вы можете сделать это, используя

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;
  }
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...