从其他状态继承转换值

Inherit transform-value from other state

我有一张图片,它会在悬停时缩放。但是,同时图像在 X 轴和 Y 轴上都转换为 -50%,或者在某些情况下,仅在 X 轴上转换。

有没有办法继承之前的转换,同时仍然改变其中一个值?

.container {
  position: relative;
  height: 400px;
  width: 640px;
  overflow: hidden;
}

img {
  -webkit-transform: translate(-50%,-50%) scale(1);
  transform: translate(-50%,-50%) scale(1);
  position: absolute;
  top: 50%;
  left: 50%;
  transition: 500ms;
}

img.special {
  -webkit-transform: translateX(-50%) scale(1);
  transform: translateX(-50%) scale(1);
  top: 0;
}

img:hover {
  -webkit-transform: translate(-50%, -50%) scale(1.1);
  transform: translate(-50%, -50%) scale(1.1);
}
<div class="container">
  <img src="http://www.lorempixel.com/640/400/nature" alt="test image" />
</div>
<div class="container">
  <img src="http://www.lorempixel.com/640/400/abstract" class="special" alt="test image" />
</div>

TL:DR; 有没有办法继承原始转换设置,同时仍然更改其中一个值? 我 不是 寻找添加额外 css、类 或其他内容的答案。我只是在寻找一种尽可能短的方法。我已经使用额外的 类 和 CSS.

解决了这个问题

Is there a way to inherit the original transform settings, while still changing one of the values?

不,在 CSS 中没有办法做到这一点。 CSS transform 属性 声明(像所有其他属性一样)不是附加的。最新的设置(或)更具体的设置将完全覆盖任何其他指定的设置,因此没有机会 继承 一些值并在其之上添加。

纯 CSS 的唯一替代方法是添加一个额外的包装器并对其应用其中一个转换。这样,img:hover 样式(scale)就不需要重复,可以保持通用。

.container {
  position: relative;
  height: 400px;
  width: 640px;
  overflow: hidden;
}
.wrapper {
  -webkit-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  position: absolute;
  top: 50%;
  left: 50%;
}
.special.wrapper {
  -webkit-transform: translateX(-50%);
  transform: translateX(-50%);
  top: 0;
}
.wrapper img {
  transition: 500ms;
}
img:hover {
  -webkit-transform: scale(1.1);
  transform: scale(1.1);
}
<div class="container">
  <div class="wrapper">
    <img src="http://www.lorempixel.com/640/400/nature" alt="test image" />
  </div>
</div>
<div class="container">
  <div class="wrapper special">
    <img src="http://www.lorempixel.com/640/400/people" alt="test image" />
  </div>
</div>

另一种方法是使用 JavaScript,找出元素上的当前变换是什么,然后在悬停时附加额外的变换并通过内联样式应用它。