3
3

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.

JavaScript で transition を持つ要素の display を変更する際に気をつけること

Last updated at Posted at 2016-02-10

問題

以下のような HTML があったとき、直観的にはマウスオーバーでふわっと出てきそうなのですが、Webkit 系のブラウザや Firefox では transition が効かず mouseenter で即表示されてしまいます。 (IE ではこのコードでも transition が効きます)

<div id="marker"></div>
<div id="square"></div>
<style type="text/css">
#marker {
  width: 100px;
  height: 10px;
  background: black; 
}
#square {
  width: 100px;
  height: 100px;
  background: red; 
  display: none;
  opacity: 0;
  transition: all 1s;
}
</style>
<script type="text/javascript">
(function() {
  var marker = document.getElementById("marker");
  var square = document.getElementById("square");
  marker.addEventListener("mouseenter", function() {
    square.style.display = "block";
    square.style.opacity = "1";
  });
  marker.addEventListener("mouseleave", function() {
    square.style.display = "";
    square.style.opacity = "";
  });
})();
</script>

ワークアラウンド

display: none/block の代わりに visibility: hidden/visible を使うか、setTimeout で時間差でプロパティを変化させると、transition させることができるようです。

<script type="text/javascript">
(function() {
  var marker = document.getElementById("marker");
  var square = document.getElementById("square");
  marker.addEventListener("mouseenter", function() {
    square.style.display = "block";
    setTimeout(function() {
      square.style.opacity = "1";
    }, 10);
  });
  marker.addEventListener("mouseleave", function() {
    square.style.display = "";
    square.style.opacity = "";
  });
})();
</script>
3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?