【问题标题】:How to apply transition only on transform: translateX()?如何仅在变换上应用过渡:translateX()?
【发布时间】:2022-09-23 16:45:12
【问题描述】:

body{
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;

}
div {
  height: 50px;
  width: 200px;
  background: rgb(255, 99, 99);
}
div:hover{
  transform: translateX(100px) rotateZ(45deg);
  transition: transform 2s;
}
<!DOCTYPE html>
<html lang=\"en\">
<head>
    <meta charset=\"UTF-8\">
    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">
    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">
    <title>Document</title>
</head>
<body>
    <div>Hover on me.</div>
</body>
</html>

我只想在translateX() 上应用过渡,而不是在rotateZ() 上。

就像是transition: translateX 1s;.有什么办法吗? (Chrome 浏览器)。

  • 不,这不是直接可能的。您只能在属性上转换 - transform这里的属性,translateX(100px) rotateZ(45deg) 是它的值。为此,您必须使用两个嵌套元素,以便您可以分别应用平移和旋转 - 然后您可以仅在其中一个元素上进行转换。
  • 那么您是否希望在悬停时立即应用旋转然后开始转型转型?

标签: css google-chrome css-animations css-transitions


【解决方案1】:

这是使用keyframes 实现此目的的一种hacky 方法。请注意,您需要在 div 移动时移动光标,以保持悬停状态。

body {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

div {
  height: 50px;
  width: 200px;
  background: rgb(255, 99, 99);
}

div:hover {
  animation: onlyTranslate 1s linear forwards;
}

@keyframes onlyTranslate {
  0% {
    transform: translateX(0px) rotateZ(0deg);
  }
  1% {
    transform: translateX(0px) rotateZ(45deg);
  }
  100% {
    transform: translateX(100px) rotateZ(45deg);
  }
}
&lt;div&gt;Hover on me.&lt;/div&gt;

【讨论】:

    【解决方案2】:

    您可以使用单独的转换,但请注意浏览器支持,因为它是一项新功能

    body{
      height: 100vh;
      display: flex;
      justify-content: center;
      align-items: center;
    
    }
    div {
      height: 50px;
      width: 200px;
      background: rgb(255, 99, 99);
      transition: translate 2s;
    }
    body:hover div{
      translate: 100px 0;
      rotate: 45deg;
    }
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <div>Hover on me.</div>
    </body>
    </html>

    【讨论】:

    • 您如何指代“个体转换”?我在caniuse 上找不到它。不错的功能,从来不知道这个!
    • @SigurdMazanti 它们是经典属性,您所要做的就是单独搜索每一个
    猜你喜欢
    • 2018-12-12
    • 1970-01-01
    • 2014-08-08
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 2013-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多