How to dynamically create CSS class in JavaScript and apply?

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

    As of IE 9. You can now load a text file and set a style.innerHTML property. So essentially you can now load a css file through ajax (and get the callback) and then just set the text inside of a style tag like this.

    This works in other browsers, not sure how far back. But as long as you don't need to support IE8 then it would work.

    // RESULT: doesn't work in IE8 and below. Works in IE9 and other browsers.
    $(document).ready(function() {
        // we want to load the css as a text file and append it with a style.
        $.ajax({
            url:'myCss.css',
            success: function(result) {
                var s = document.createElement('style');
                s.setAttribute('type', 'text/css');
                s.innerHTML = result;
                document.getElementsByTagName("head")[0].appendChild(s);
            },
            fail: function() {
                alert('fail');
            }
        })
    });
    

    and then you can have it pull an external file like the myCss.css

    .myClass { background:#F00; }
    

提交回复
热议问题