简体   繁体   中英

How to prevent transition-delay when reversd

I have a <div> , I want to double its width and height when hover .
But I want the width to be transitioned first and then height .
And when reversing (mouse moved out), I want the height to be transitioned first, then height .
(Just an epitome of complex transitions, to demonstrate the issue)

 .box { background-color: pink; width: 100px; height: 100px; transition: width 1s 1s, height 1s 0s; }.box:hover { width: 200px; height: 200px; transition-delay: 0s, 1s; }
 <.DOCTYPE html> <html lang="en"> <head> <title>Home</title> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width" /> <link rel="stylesheet" href="styles.css" /> <script type="module" src="script.js"></script> </head> <body> <div class="box"></div> </body> </html>

In the example above, if I remove the mouse when transitioning height , everything is OK.
But if I remove the mouse when transitioning width , I have to wait 1s which is the transition-duration of height part (actually because of the transition-delay ) before the reverse transition of width starts, which leads to awful result when the transition queue is complex.
Vice versa, if I hover the element again when transitioning height backwards, I have to wait for 1s until I can see height animating, because of the 1s delay. I'm expecting to see width transitioning backwards immediately after I remove the mouse.


Here is an example of a complex transition queue: CSS Gradient neon button with hover effect


Is there any way to prevent the problem just by CSS transitions?

One trick is to avoid transition-delay by playing with max-width and min-height so both width and height will run at the same time.

You make the width go to 400px but with a max-width of 200px and height should start at 0 with a min-height of 100px . Like that each property will get blocked at half the transition which will simulate the delay:

 .box { background-color: pink; width: 100px; height: 0; max-width: 200px; min-height: 100px; transition: 2s; }.box:hover { width: 400px; height: 200px; }
 <div class="box"></div>

<script>
  function bigImg(x) {
    x.style.height = "200px";
    x.style.width = "200px";
  }

  function normalImg(x) {
    x.style.height = "100px";
    x.style.width = "100px";
  }
</script>
<div class="box" onmouseover="bigImg(this)" onmouseout="normalImg(this)"></div>

and then simply remove the .box:hover css completely

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