How to hide elements with jQuery before they get rendered?

后端 未结 12 1326
北恋
北恋 2020-12-13 08:51

I want to generate html layout with areas (divs, spans) that can be shown/hidden conditionally. These areas are hidden by default.

If I call .hide() method with jque

12条回答
  •  不知归路
    2020-12-13 09:25

    I agree with Boris Guéry, that it is not over-engineering, but rather, a standard best practice. I would go a slightly different way than Boris, by adding a no-js class to the html initially and then removing it with JavaScript.

    This way you're not waiting for the document to be ready to hide the content, and without any JavaScript you still see the content. Assuming the user has not JavaScript is more in line with the philosophy of progressive enhancement.

    ex:

    
    
    

    my css :

    #foo {
        display: none;
    }
    html.no-js #foo {
        display: block;
    }
    

    and javascript

    $(document).ready(
       function()
       {
         $('html').removeClass('no-js');
       }
    );
    

    ********* OR on a per-case basis***********

    ex:

    foobar and stuff

    css:

    .no-js {
      display:none;
    }
    #foo {
      display: block;
    }
    #foo.no-js {
      display: none;
    }
    

    js:

    $(document).ready(function(){
      // remove the class from any element that has it.
      $('.no-js').removeClass('no-js');
    });
    

提交回复
热议问题