简体   繁体   中英

jQuery/CSS add fade-in and fade out effect

I have made 3 css classes which look like this:

.modal {
    display: none;
    position: fixed;
    z-index: 1000;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    background: rgba( 255, 255, 255, .8 ) url('') 50% 50% no-repeat;
    background-image: url('../../images/gears.svg');
}

body.loading {
    overflow: hidden;
}

    body.loading .modal {
        display: block;
    }

Upon jQuery event onclick I display to the end user so the user knows something's happening.

What I don't like here is that the loading appears very forcingly , there is no smoothness in transition when it appears and when it disappears. What I do to show the loading gears to user is:

$body = $("body");

And then to display it:

$body.addClass("loading");

Or to remove it:

$body.removeClass("loading");

How can I add smooth transition of when the loading gears appear and disappear using jquery or CSS so that the animation looks more friendly?

Can someone help me out ?

I would remove display: none then just use a css transition to fade in the container. You can also just add the class to the modal instead of to the body.

.loader {
  visibility: hidden;
  opacity: 0;
}

.loader.visible {
   opacity: 1;
   visibility: visible;
   transition: opacity .25s ease-in-out;
   -moz-transition: opacity .25s ease-in-out;
   -webkit-transition: opacity .25s ease-in-out;
}

Aside from using CSS transitions with opacity or visibility you can also just use jQuery to show/hide the loader. I would recommend Zach's CSS solution as it's simpler and more performant, but this is an alternative.

 .modal {
  display: none;
  position: fixed;
  z-index: 1000;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  background: rgba( 255, 255, 255, .8 ) url('') 50% 50% no-repeat;
  background-image: url('../../images/gears.svg');
}
body.loading {
  overflow: hidden;
}

$('body').addClass('loading');

/* fade loader in */
$('.modal').fadeIn('fast');

/* fade loader out */
$('.modal').fadeOut('fast', function() {
  $('body').removeClass('loading');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM