How to dynamically create CSS class in JavaScript and apply?

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

    YUI has by far the best stylesheet utility I have seen out there. I encourage you to check it out, but here's a taste:

    // style element or locally sourced link element
    var sheet = YAHOO.util.StyleSheet(YAHOO.util.Selector.query('style',null,true));
    
    sheet = YAHOO.util.StyleSheet(YAHOO.util.Dom.get('local'));
    
    
    // OR the id of a style element or locally sourced link element
    sheet = YAHOO.util.StyleSheet('local');
    
    
    // OR string of css text
    var css = ".moduleX .alert { background: #fcc; font-weight: bold; } " +
              ".moduleX .warn  { background: #eec; } " +
              ".hide_messages .moduleX .alert, " +
              ".hide_messages .moduleX .warn { display: none; }";
    
    sheet = new YAHOO.util.StyleSheet(css);
    

    There are obviously other much simpler ways of changing styles on the fly such as those suggested here. If they make sense for your problem, they might be best, but there are definitely reasons why modifying css is a better solution. The most obvious case is when you need to modify a large number of elements. The other major case is if you need your style changes to involve the cascade. Using the dom to modify an element will always have a higher priority. Its the sledgehammer approach and is equivalent to using the style attribute directly on the html element. That is not always the desired effect.

提交回复
热议问题