正如我们所知,更改元素外观时会发生重绘,而更改布局时会发生重排。但是,我有一个问题,当更改img src属性时,是否会导致回流。
例如,有两个不同大小的图像,分别称为A.png和B.png。
html:
<button>change image src<button>
<img src="A.png">然后我们将img src改为js:
document.querySelector('button').onclick = function() {
document.querySelector('img').src = 'B.png';
}因为A.png和B.png的大小不同,所以在更改img src时会导致重绘和回流。
但是如果我们通过css来固定img的大小,如下所示:
img {
width: 100px;
height: 100px;
}如果我们再次更改img src,是否会导致重绘和回流?
发布于 2019-04-03 14:08:15
这可能会导致重画,但不会导致回流,Check this Visualization
它发生在几秒钟内,我们甚至没有注意到这一切的发生。
发布于 2019-04-03 14:39:07
如果你使用css,用javascript修改src属性只会重绘,不会回流,因为html图像元素的尺寸是固定的,即使实际图像的尺寸是不同的。
在按钮上的单击事件发生之前,css已经处于活动状态,因此没有图像回流。
以下示例不会导致回流。
document.querySelector('button').onclick = function () {
document.querySelector('img').src = 'https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500';
}img {
width: 100px;
height: 100px;
}<button>change image src<button>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.</p>
<img src="https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500">
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.</p>
这将导致回流,
document.querySelector('button').onclick = function () {
document.querySelector('img').src = 'https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500';
}<button>change image src<button>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.</p>
<img src="https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500">
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s.</p>
https://stackoverflow.com/questions/55487927
复制相似问题