How to prevent css from getting converted to inline css

前端 未结 2 1083
栀梦
栀梦 2021-01-26 10:42

I am using jquery to modify css of a div element on pressing a button. I noticed the css getting inline to the HTML. How can I prevent the style from getting inline ?

         


        
2条回答
  •  面向向阳花
    2021-01-26 11:00

    I am using jquery to modify css of a div element on pressing a button.

    The most obvious would of course be to add/remove/toggle a class with a predefined rule, like this,

    CSS

    .wider {
      width: 500px;
    }
    

    Script

    $( "element" ).toggleClass( "wider" );
    

    but if that is not what you look for, you can add a style element dynamically, to override an existing rule

    JS

    function loadStyle(css) {
      var style = document.querySelector('style[id="lastinbody"]') || document.createElement('style');
      style.id = 'lastinbody';
      style.type = 'text/css';
      if (style.styleSheet){
        style.styleSheet.cssText = css;
      } else {
        style.appendChild(document.createTextNode(css));
      }
      document.querySelector('body').appendChild(style);
    }
    

    Usage

    loadStyle('.item { color: red; }');
    

    I noticed the css getting inline to the HTML.

    If you want the style being added to the head, do like this

    JS

    function loadStyle(css) {
      var style = document.querySelector('head style[id="addedinhead"]') || document.createElement('style');
      style.id = 'addedinhead';
      style.type = 'text/css';
      if (style.styleSheet){
        style.styleSheet.cssText = css;
      } else {
        style.appendChild(document.createTextNode(css));
      }
      document.querySelector('head').appendChild(style);
    }
    

    And here is how to push a CSS file

    var style = document.createElement('link');
    style.rel = 'stylesheet';
    style.type = 'text/css';
    style.media = 'screen';
    style.href = 'css-file-path';
    document.querySelector('head').appendChild(style);
    

    And this one shows how to add to an existing linked stylesheet

    HTML

    
      
    
    

    JS

    function setStyleSheetRule(title, rule) {
      for(var i=0; i

    Read more: https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/insertRule

提交回复
热议问题