Can I use non existing CSS classes?

后端 未结 13 1942
北荒
北荒 2020-11-27 12:54

I have a table where I show/hide a full column by jQuery via a CSS class that doesn\'t exist:

13条回答
  •  北海茫月
    2020-11-27 13:55

    One thing that nobody here has fully mentioned is that JavaScript (aided by jQuery in this case) isn't able to directly modify a document's cascading style sheet. jQuery's css() method merely changes the matched set of elements' style property. CSS and JavaScript are completely unrelated in this aspect.

    $('.target').css('display','none'); doesn't change your .target { } CSS declaration at all. What has happened here instead is that any element with a class of "target" now looks something like this:

    
    

    Are there any side effects caused by not pre-defining a CSS style rule? None whatsoever.

    Is there a better way to do this? Performance-wise, yes there is!

    How can the performance be improved?

    Rather than directly modifying the style of each element, instead you can pre-define a new class and add that to your matched elements using addClass() (another jQuery method).

    Based on this pre-existing JSPerf which compares css() with addClass(), we can see that addClass() is actually much faster:

    css() vs addClass()

    How can we implement this ourselves?

    Firstly we can add in our new CSS declaration:

    .hidden {
        display: none;
    }
    

    Your HTML would remain the same, this pre-defined class is simply in place for later use.

    We can now modify the JavaScript to use addClass() instead:

    $('.target').addClass('hidden');
    

    When running this code, rather than directly modifying the style property of each of your matched "target" elements, this new class will now have been added:

    
    

    With the new "hidden" class, this element will inherit the styling declared in your CSS and your element will be set to no longer display.

提交回复
热议问题