2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

要素のfadein,fadeoutをjavascriptとcssで実装してみた

Posted at

要素のfadein,fadeoutの実装したのでメモ

今回作ったもの

ページをリロードした瞬間に要素をフワ〜とfadeInで表示させ、
5秒後にフワ〜と消すものを実装した。

コード

HTML

.html
<div class="wrapper" data-wrapper="">
  <p class="text">これはサンプルです。</p>
</div>

CSS(sass)

.css
@keyframes fadeIn {
    0% {
        opacity: 0;
    }
    100% {
        opacity: 1;
    }
}
@keyframes fadeOut {
    0% {
        opacity: 1;
    }
    100% {
        opacity: 0;
    }
}

.wrapper {
  border: 1px solid #333;
  animation: fadeIn 2s;
  animation-fill-mode: both;
  
  &--fadeOut {
    animation: fadeOut 1.2s;
    animation-fill-mode: both;
  }
}

.text {
  margin: 0;
  padding: 12px;
}

javascript

.js
const wrapper = document.querySelector('[data-wrapper]');

let i = 0;

const interval = setInterval(() => { // タイマー処理(第二引数に入ってる値ごとに処理を繰り返す)
  if (i < 5) {
  	i += 1;
  } else {
    wrapper.classList.add('wrapper--fadeOut');
  	clearInterval(interval); // タイマー処理(intervalを止める)
  }
}, 1000);
2
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?