jQuery, hide a div without disturbing the rest of the page

前端 未结 6 483
难免孤独
难免孤独 2020-12-17 21:37

Consider the page as below (pseudocode)

&l
相关标签:
6条回答
  • 2020-12-17 21:59

    Use visibility:hidden, it will hide the element just like display:none but the layout doesn't change.

    You can use animate function. e.g.

     $('#header').animate({opacity: 0}, 2000);
    
     $("#header").hover(
         function() {  
           $(this).animate({opacity: 1}, 400);
           // you can also use one of the below
           // $(this).css("opacity","1"); 
           // $(this).fadeTo(400, 1);
         },
         function() { 
           $(this).animate({opacity: 0}, 400);
         }
     );
    

    You can also use fadeTo as mentioned by Nick. fadeTo internally sets the opacity equal to the second parameter.

    0 讨论(0)
  • 2020-12-17 22:02

    Add a container around the header, and style it with display:block and a fixed width/height. When you fade out the header, the container will preserve the space the header occupied.

    This way you have an element to bind the hover event to, for re-displaying the header after it's faded out. Once hidden, the header will not be able to receive its own hover events, so the container must receive them in its place.

    0 讨论(0)
  • 2020-12-17 22:06

    .fadeOut() finishes with a display: none;, if you don't want to do that, use .fadeTo() instead (which won't set display at the end), like this:

    $("header").delay(5000).fadeTo(2000, 0);
    

    (note this uses the built-in .delay() function)

    You can try out a full demo here, with the hover functionality fading and not causing movement as well, like this:

    $("header").hover(function() { 
      $(this).fadeTo(600, 1); 
    }, function() { 
      $(this).fadeTo(600, 0); 
    });
    
    0 讨论(0)
  • 2020-12-17 22:11

    Try adding a callback to the hide function that changes it to visibility hidden.

    $(this).hide("slow", function(){
       $(this).css("visibility", "hidden");
       $(this).css("display", "block");
    });
    

    It would be nice if jQuery let you specify whether to use display or visibility when hiding something, but I don't think it does.

    0 讨论(0)
  • 2020-12-17 22:21

    Position your header absolutely, that way its presence (or lack thereof) will not affect the other page elements

    0 讨论(0)
  • 2020-12-17 22:22

    You could just put the header inside another and style that div to be the same height as the header. Then if jQuery removed the header it won't effect the page.

    Alternatively, as Lobo says, you could make it use visibility:hidden, but I imagine it will be hard to force jQuery not to set it display: none anyway.

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