jQuery .show() a flex box

前端 未结 9 1292
南笙
南笙 2021-02-06 20:56

I have an element with a flexbox

    div#myFlexbox{ display:flex; }

after hide it and show it, it gets messed up.<

相关标签:
9条回答
  • 2021-02-06 21:38

    Since other answers did not account for the possibility that you might be using the duration argument...

    Short Answer: Use .hide for hiding the value and that shouldn't happen.

    A little explanation:

    The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css( "display", "none" ), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value. If an element has a display value of flex and is hidden then shown, it will once again be displayed flex.

    From documentation, Changed 'inline' to 'flex' to fit the contenxt!

    So jQuery knows what you're hiding! If you've hidden it using .hide that is, And it knows how to show it again with the right display value.

    0 讨论(0)
  • 2021-02-06 21:39

    I know it is a little too late (3 years) but this is the way I managed to do it.

    I created a rule in css for my div, for example #myDiv, that goes like this

    #myDiv[style*='block'] {
        display: inline-flex !important;
    }
    

    It takes advantage of what jQuery does to the DOM, it applies 'display:block'. I used inline-flex because i needed it for what i'm doing, but it can be whatever you want. In this way the rule goes faster applied without any flickering.

    0 讨论(0)
  • 2021-02-06 21:41

    JQuery .show() doesn't know about your display: flex; (not flexbox). Instead try to add and remove a hiding class.

    CSS:

    #myFlexbox{
      display: flex;
    }
    
    .hide{
      display: none !important;
    }
    

    JS:

    $('#myFlexbox').addClass('hide');
    $('#myFlexbox').removeClass('hide');
    

    https://jsfiddle.net/p2msLqtt/

    Otherwise you have to execute your JS after the CSS is completely loaded and DOM is ready I guess - i.e. like:

    <html>
      <head>
        <!-- CSS -->
      </head>
      <body>
        <!-- BODY PART -->
        <!-- SCRIPT TO HIDE AND SHOW -->
      </body>
    </html>
    

    Updated the fiddle and set Javascript execution to domready - it's working:

    https://jsfiddle.net/p2msLqtt/1/

    0 讨论(0)
提交回复
热议问题