How do you add CSS with Javascript?

前端 未结 14 2630
旧时难觅i
旧时难觅i 2020-11-22 17:18

How do you add CSS rules (eg strong { color: red }) by use of Javascript?

14条回答
  •  心在旅途
    2020-11-22 17:57

    Here's a slightly updated version of Chris Herring's solution, taking into account that you can use innerHTML as well instead of a creating a new text node:

    function insertCss( code ) {
        var style = document.createElement('style');
        style.type = 'text/css';
    
        if (style.styleSheet) {
            // IE
            style.styleSheet.cssText = code;
        } else {
            // Other browsers
            style.innerHTML = code;
        }
    
        document.getElementsByTagName("head")[0].appendChild( style );
    }
    

提交回复
热议问题