How to dynamically create CSS class in JavaScript and apply?

后端 未结 15 1013
长情又很酷
长情又很酷 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: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)
    

提交回复
热议问题