How to prevent css from getting converted to inline css

前端 未结 2 1081
栀梦
栀梦 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 10:52

    Link your stylesheet in head

    <head>
      <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    
    0 讨论(0)
  • 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

    <head>
      <link title="customCSS" rel="stylesheet" type="text/css" href="style.css">
    </head>
    

    JS

    function setStyleSheetRule(title, rule) {
      for(var i=0; i<document.styleSheets.length; i++) {
        var sheet = document.styleSheets[i];
        if(sheet.title == title) {
          sheet.insertRule(rule, sheet.cssRules.length);
        }
      }
    }
    
    setStyleSheetRule('customCSS', '.have-border { border: 1px solid black;}')
    

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

    0 讨论(0)
提交回复
热议问题