CSS 变换与位置 [英] CSS transform vs position
问题描述
请向我解释转换位置 left
或 right
属性或 -transform: translateX(n)
的区别,因为两者似乎都达到了相同的目的,但可以独立应用.我了解硬件加速的可能性,但这取决于实施.
Can some please explain to me the difference in transitioning the positional left
or right
properties or the -transform: translateX(n)
, as the both seem to achieve the same thing yet can be applied independently. I understand about the possibility of hardware acceleration but that's dependent on implementation.
// psuedo code;
#box {
-transition-property: all;
-transition-duration: 1s;
}
// javascript
box.style.transform = "translateX(200px)";
vs
box.style.left = "200px";
一个比另一个有什么优势?谢谢,
What's the advantage of one over the other? Thanks,
p
推荐答案
渲染层的绘制顺序为:
- 布局层
- 绘制层
- 合成层
一个图层的重绘会触发后续图层的重绘.
A redraw in a layer will trigger redraw in subsequent layers.
改变left
或margin
会触发布局层的重绘(反过来,会触发其他两层的重绘)用于动画元素和 DOM 中的后续元素.
Changing left
or margin
will trigger a redraw in layout layer (which, in turn, will trigger redraws in the other two layers) for the animated element and for subsequent elements in DOM.
更改transform
将在合成器层中触发重绘仅针对动画元素(DOM 中的后续元素不会强>被重绘).
Changing transform
will trigger a redraw in compositor layer only for the animated element (subsequent elements in DOM will not be redrawn).
性能(因此是每秒帧数,或者简单来说,动画平滑度)的差异是巨大的.使用第一种技术即使在良好的机器上(处理器繁忙时)也经常会导致动画抖动,而第二种技术即使在资源有限的系统上也可能运行平稳.
The difference in performance (hence in frames per second or, in simple terms, in animation smoothness) is tremendous. Using the first technique will often result in jittery animations even on good machines (when the processor is busy), while the second will likely run smoothly even on systems with limited resources.
使用 transform
的另一个优点是合成器重绘得到了大量优化(多个元素的动画会导致对所有元素的重绘),而更改布局层将在每个元素的每次更改后触发重绘.
Another advantage of using transform
s is compositor redraws are heavily optimized (animations to multiple elements result in one redraw for all), while changing layout layer will trigger a redraw after each change of each element.
有关渲染技术和渲染性能的更详细说明,我推荐 Google 的Web Fundamentals.
For a more detailed explanation on rendering techniques and rendering performance I recommend Google's Web Fundamentals.
这篇关于CSS 变换与位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!