【问题标题】:Is it possible to maintain object-fit during a CSS transform?是否可以在 CSS 转换期间保持对象匹配?
【发布时间】:2021-01-04 12:59:04
【问题描述】:

我正在开发一个组件,它将图像从开始位置 + 比例转换为结束位置 + 比例(即填满屏幕)。这是通过translatescale 上的CSS 变换动画完成的。

挑战在于,组件用户可能会使用object-fit 属性更改要转换的某些图像。但是,CSS translate 似乎在翻译期间不维护 object-fit 属性。

此处为 Codepen 示例:https://codepen.io/cathyxz/pen/mXgEMB

我知道我可以在技术上为widthheight 设置动画,但出于性能原因,我想保持浏览器可以animate cheaply 的属性,即不影响布局,这让我们只有位置、旋转,规模,不透明度。

参考:https://www.html5rocks.com/en/tutorials/speed/high-performance-animations/

无论如何,我是否可以逐渐将我的过渡动画化为“取消裁剪”图像而不是拉伸它们?

【问题讨论】:

  • 你想影响布局,所以不,不是object-fit

标签: javascript css css-animations css-transforms


【解决方案1】:

object-fit 应用于转换前的元素。

无论对象上所有 CSS 的结果如何,transform 都会接受并应用转换。事实上,该元素在 DOM 中保持不变。这就是为什么transform 不会触发重绘(并且被认为是高效的)。只有它的渲染(复合层)被转换。由于变换,它的渲染在 X 轴上被拉伸了 4 倍。但这不会使元素宽 4 倍,因此无法按预期应用对象匹配。


你能逐渐解开吗?是的,但不是transform。为了尽可能便宜地做到这一点(不会触发后续流程的重绘),您需要:

  1. 父占位符(带有position:relative)与您的图像一样高,以保持文档流中的可用空间
  2. 要设置动画的元素,使用position:absolute。因此,即使您为width 设置动画,也不会触发layout,因为该元素在文档流之外。

.transform-placeholder {
  height: 100px;
  position: relative;
}

.transform-placeholder .object-fit {
  width: 100px;
  height: 100px; 
  animation: object-fit 2.1s infinite;
  animation-timing-function: cubic-bezier(.4,0,.2,1);
  
}

@keyframes object-fit {
  0% {
    width: 100px;
  }
  50% {
    width: 400px;
  }
  100% {
    width: 100px;
  }
}
<div class="transform-placeholder">
  <div class="object-fit" style="background-image: url('https://picsum.photos/1600/400?image=857')">
  </div>
</div>

<h2>Animation above does not trigger repaint on any DOM element that's outside the animated div.</h2>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-31
    • 2023-01-13
    • 2010-10-29
    • 2015-11-28
    相关资源
    最近更新 更多