简体   繁体   中英

CSS transitions: Why won't my CSS transition work as I expect?

I have a flash message div at the top of my page for when the site wants to display any messsages to the user.

I want the flash message to fade out after a couple of seconds. I'm using a CSS transition.

Here is my code:

.flash {
  position: fixed;
  opacity: 1;
  visibility: visible;
  transition: opacity 2s ease-in, visibility 2s ease-in;
}

.hide {
  visibility: hidden;
  opacity: 0;
}
document.querySelectorAll('.flash').forEach(function(flash){
  flash.classList.toggle('hide');
})

I expect that when the page loads, the div will be visible before fading out. But, in Safari, when the page loads, .flash is invisible.

In Chrome, the page loads and the .flash div fades as expected. However, on reloading the page, the div still has the .hide class attached and so the flash message remains invisible. (I can store state in HTML?,,) Strangely. in Chrome, it works if I'm inspecting an element in the document with developer tools when I reload the page.

Now I'm highly confused.

Why does .hide remain attached to the div across page reloads?

Why does Safari fail to display the div at all?

EDIT: after your comment reply, what you need to do is trigger the fadeout on a focus event.

.flash:focus {
  //use the fadeout code here
}

The reason is the toggle, your browser saves the state of the page in the browser's cache but not the javascript that is dynamically changing the css on reload, on and off.

Instead of manipulating the css with javascript, google fade out with css.

.fade-out {
  animation: fadeOut ease 10s;
  -webkit-animation: fadeOut ease 10s;
  -moz-animation: fadeOut ease 10s;
  -o-animation: fadeOut ease 10s;
  -ms-animation: fadeOut ease 10s;
}
@keyframes fadeOut {
  0% {
    opacity:1;
  }
  100% {
    opacity:0;
  }
}

it's a lot smoother this way, and you can test it more easily with the developer tools.

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