How to dynamically create CSS class in JavaScript and apply?

后端 未结 15 1006
长情又很酷
长情又很酷 2020-11-22 02:57

I need to create a CSS stylesheet class dynamically in JavaScript and assign it to some HTML elements like - div, table, span, tr, etc and to some controls like asp:Textbox,

相关标签:
15条回答
  • 2020-11-22 03:48

    For the benefit of searchers; if you are using jQuery, you can do the following:

    var currentOverride = $('#customoverridestyles');
    
    if (currentOverride) {
     currentOverride.remove();
    }
    
    $('body').append("<style id=\"customoverridestyles\">body{background-color:pink;}</style>");
    

    Obviously you can change the inner css to whatever you want.

    Appreciate some people prefer pure JavaScript, but it works and has been pretty robust for writing/overwriting styles dynamically.

    0 讨论(0)
  • 2020-11-22 03:51

    https://jsfiddle.net/xk6Ut/256/

    One option to dynamically create and update CSS class in JavaScript:

    • Using Style Element to create a CSS section
    • Using an ID for the style element so that we can update the CSS
      class

    .....

    function writeStyles(styleName, cssText) {
        var styleElement = document.getElementById(styleName);
        if (styleElement) 
                 document.getElementsByTagName('head')[0].removeChild(
            styleElement);
        styleElement = document.createElement('style');
        styleElement.type = 'text/css';
        styleElement.id = styleName;
        styleElement.innerHTML = cssText;
        document.getElementsByTagName('head')[0].appendChild(styleElement);
    }
    

    ...

        var cssText = '.testDIV{ height:' + height + 'px !important; }';
        writeStyles('styles_js', cssText)
    
    0 讨论(0)
  • 2020-11-22 03:55

    Found a better solution, which works across all browsers.
    Uses document.styleSheet to add or replace rules. Accepted answer is short and handy but this works across IE8 and less too.

    function createCSSSelector (selector, style) {
      if (!document.styleSheets) return;
      if (document.getElementsByTagName('head').length == 0) return;
    
      var styleSheet,mediaType;
    
      if (document.styleSheets.length > 0) {
        for (var i = 0, l = document.styleSheets.length; i < l; i++) {
          if (document.styleSheets[i].disabled) 
            continue;
          var media = document.styleSheets[i].media;
          mediaType = typeof media;
    
          if (mediaType === 'string') {
            if (media === '' || (media.indexOf('screen') !== -1)) {
              styleSheet = document.styleSheets[i];
            }
          }
          else if (mediaType=='object') {
            if (media.mediaText === '' || (media.mediaText.indexOf('screen') !== -1)) {
              styleSheet = document.styleSheets[i];
            }
          }
    
          if (typeof styleSheet !== 'undefined') 
            break;
        }
      }
    
      if (typeof styleSheet === 'undefined') {
        var styleSheetElement = document.createElement('style');
        styleSheetElement.type = 'text/css';
        document.getElementsByTagName('head')[0].appendChild(styleSheetElement);
    
        for (i = 0; i < document.styleSheets.length; i++) {
          if (document.styleSheets[i].disabled) {
            continue;
          }
          styleSheet = document.styleSheets[i];
        }
    
        mediaType = typeof styleSheet.media;
      }
    
      if (mediaType === 'string') {
        for (var i = 0, l = styleSheet.rules.length; i < l; i++) {
          if(styleSheet.rules[i].selectorText && styleSheet.rules[i].selectorText.toLowerCase()==selector.toLowerCase()) {
            styleSheet.rules[i].style.cssText = style;
            return;
          }
        }
        styleSheet.addRule(selector,style);
      }
      else if (mediaType === 'object') {
        var styleSheetLength = (styleSheet.cssRules) ? styleSheet.cssRules.length : 0;
        for (var i = 0; i < styleSheetLength; i++) {
          if (styleSheet.cssRules[i].selectorText && styleSheet.cssRules[i].selectorText.toLowerCase() == selector.toLowerCase()) {
            styleSheet.cssRules[i].style.cssText = style;
            return;
          }
        }
        styleSheet.insertRule(selector + '{' + style + '}', styleSheetLength);
      }
    }
    

    Function is used as follows.

    createCSSSelector('.mycssclass', 'display:none');
    
    0 讨论(0)
提交回复
热议问题