如何仅在变换上应用转换:translateX()?

问题描述 投票:0回答:3

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 浏览器)。

html css google-chrome css-animations css-transitions
3个回答
5
投票

您可以使用单独的变换

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>


2
投票

这是一种使用

keyframes
实现此目的的巧妙方法。请注意,您需要随着 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);
  }
}
<div>Hover on me.</div>


1
投票

您可以尝试使用关键帧动画而不是过渡。 将rotateZ() 放在它应该触发的% 范围内。 否则,你可以尝试 JS 实现,如果需要示例请告诉我。

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

}
div {
  height: 50px;
  width: 200px;
  background: rgb(255, 99, 99);
}
div:hover {
  animation: move 2s normal forwards ease-in-out;
}

@keyframes move {
    0%   {
      transform: translateX(0px) rotateZ(0deg);
    }
    95% {
      transform: translateX(100px) rotateZ(0deg);    
    }
    100% {
      transform: translateX(100px) rotateZ(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>

© www.soinside.com 2019 - 2024. All rights reserved.