Creating a CSS class in jQuery

前端 未结 4 2140
[愿得一人]
[愿得一人] 2020-12-04 14:37

I believe the .addClass() function in jQuery attaches a CSS class to the current selection, but I was wondering I could create or define a CSS class in jQuery, and then atta

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-04 15:12

    Actually, you can create a CSS rule that will affect all elements on the current page. In most browsers it should be as simple as:

    var style = $('')
    $('html > head').append(style);
    

    This may or may not work in IE, however you can use IE's proprietary addRule instead:

    document.styleSheets[0].addRule('body', 'background: green', -1);
    

    Naturally this will not assist you in creating css files that can be shared between webpages, but it is a handy way of affecting the style of a large number of elements without the need to iterate over them.

提交回复
热议问题