LoginSignup
21
21

More than 5 years have passed since last update.

javascript で fadeOut() したい

Posted at

opacityだけじゃなく、display:noneにもしたいのだ。
jQueryだとものすごく簡単にできるが、jQueryが使用できない場面とか、ふとjQueryじゃなくjsだけで書いてみようかな気持ちのときに。

まずはjQueryのfadeOut

これだけで、ふわっと消えるってほんと便利ですよね。

inedx.html
<p id="text">This is a pen.</p>
app.js
$('#text').click(function() {
  $('#text').fadeOut();
});

JavaScript + CSS3

ふわっとの部分をCSS3で実現。
クリック時にクラスをつけcssでopacityを、display:noneはjs側で。

inedx.html
<p id="text">This is a pen.</p>
style.css
.fadeout {
  animation : fadeOut 1s;
  animation-fill-mode: both;
}
@keyframes fadeOut {
  0% {
    opacity: 1;
  }
  100% {
    opacity: 0;
  }
}
app.js
var text = document.getElementById('text');
text.addEventListener('click', function(){
  text.classList.add('fadeout');
  setTimeout(function(){ 
    text.style.display = "none"; 
  }, 1000);
}, false);

サンプルはこちら(CodePen)
https://codepen.io/snjssk/pen/EgRGGp

21
21
0

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
21
21