jQuery fadeOut without display none?

后端 未结 6 885
死守一世寂寞
死守一世寂寞 2020-12-08 03:54

Is there an alternative to fadeOut() that doesn\'t use display:none for the style? I\'d like to just use visibility hidden to avoid any sort of shifting in the page layout?

相关标签:
6条回答
  • 2020-12-08 04:06

    Yes, there's an alternative. It's called .fadeTo(), where you set the target opacity, which in your case will be 0.

    $('element').fadeTo( 1000, 0 ); // fade to "0" with a 1000ms duration
    

    This will not alter the display property at the end.

    0 讨论(0)
  • 2020-12-08 04:07

    I you want to fadeOut, then change the content and then fadeIn again:

    $("#layer").animate({opacity: 0}, 1000, 'linear', function(){
    
        //Do here any changes to the content (text, colors, etc.)
        $("#layer").css('background-color','red'); //For example
    
        $("#layer").animate({opacity: 1}); //FadeIn again
    
    });
    
    0 讨论(0)
  • 2020-12-08 04:22

    Note that

    fadeTo(500, 0)   // fade out over half a second
    fadeTo(0, 0)     // instantly hide
    

    is (oddly) not compatible with

    fadeIn()
    

    (when you want to show it again). So if you are using

    fadeTo(500, 0)

    in order to to hide something without the css display: none then you must use

    fadeTo(500, 1)

    to fade it back in or it will still have opacity: 0 left over in the css and will remain invisible.

    0 讨论(0)
  • 2020-12-08 04:23

    You can use .animate() on the opacity directly:

    $(".selector").animate({ opacity: 0 })
    

    This way the element still occupies space like you want, it just has a 0 opacity, so it's effectively the same as it being visibility: hidden when it finishes.

    0 讨论(0)
  • 2020-12-08 04:26

    One way of doing this is to capture the display mode, then .fadeOut, and in the complete, do your preferred method of hiding, and set the display back to what it was:

    var $element = $('#selector');
    
    var display = $element.css('display');
    $element.fadeOut(500, function() {
       $element.css('visibility', 'hidden'); 
       $element.css('display', display);
    }
    
    0 讨论(0)
  • 2020-12-08 04:32

    Custom animation is an alternative http://api.jquery.com/animate/

    .animate({opacity: 0.0}, 5000, 'linear', callback);
    
    0 讨论(0)
提交回复
热议问题