简体   繁体   中英

Why is only half of my CSS transition failing on only one of my elements

https://codepen.io/u-lx/pen/QWBvQWY

Code linked above (and pieces below). I'm doing the freecodecamp random quote machine challenge. I'm trying to have the current text fade out, then have the new text fade it. It works on the quote text and author name seperately. On click, both fade out, then the author name appears suddenly just as the new text starts to fade in. I can't figure out why.

I tried wrapping both elements in a div to apply transition on a single element, but it messed with my flexbox display and I'd rather not. Here are some relevant pieces of the code:

<div id="text" class='text-show'>
      (Quotes from <a href="https://inspirobot.me/">Inspirobot</a>)
</div>
<div id="author" class='text-show'></div>
.text-show {
  opacity: 1;
  transition: all 1s ease;
}

.text-hide {
  opacity: 0;
  transition: all 1s ease;
}
function generate() {
  let random = Math.floor(Math.random() * quotes_arr.length);
  document.getElementById('text').setAttribute('class','text-hide');
  document.getElementById('author').setAttribute('class','text-hide');

  setTimeout(() => {
    document.getElementById('text').innerHTML = quotes_arr[random];
    document.getElementById('author').innerHTML = author_arr[random];
    document.getElementById('text').setAttribute('class','text-show');
    document.getElementById('author').setAttribute('class','text- show');
  },2500)
}

I think you're resetting the animation by declaring transition twice. Try applying the transition once and then simply toggling opacity with your show/hide classes:

div {
  transition: all 1s ease;
}

.text-hide {
  opacity: 0;
}

.text-show {
  opacity: 1;
}

If that still gives you trouble, you may be able to keep everything as is and just omit the second transition declaration:

.text-hide {
  transition: all 1s ease;
  opacity: 0;
}

.text-show {
  opacity: 1;
}

You typically only want to declare transition once otherwise you're instructing a second, new transition to occur.

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