jQuery show() vs adding Class

前端 未结 3 1633
小蘑菇
小蘑菇 2020-12-17 19:38

Which of these is more efficient (i.e. faster):

$(elem).show();

or

$(elem).addClass(displayClass); // Where display class i         


        
3条回答
  •  爱一瞬间的悲伤
    2020-12-17 20:09

    No, they are absolutely not identical.

    There's a big difference between direct modifications to element styles and "indirect" modifications by changing the element's class, and that really should be pretty obvious. By writing cooperative code between Javascript and CSS, the class changes give you a lot more flexibility. The Javascript manages the state of elements, while the CSS drives the actual effect of that state.

    The show() and hide() methods are handy and easy, but (in my opinion) managing state/appearance by class name is really a much more powerful and maintainable way to do things. In fact you can always write your own little jQuery plugins to add/remove classes that are meaningful to your app, to avoid having the class names themselves propagate through your code.

提交回复
热议问题