【问题标题】:Whether it will cause a reflow when changing the image's src attribution?更改图片来源属性是否会导致回流?
【发布时间】:2019-04-04 13:51:32
【问题描述】:

众所周知,更改元素皮肤时会发生重绘,更改布局时会发生重排。但是,我有一个问题,在更改 img src 属性时是否会导致回流。

例如,有两个不同大小的图像,分别称为 A.png 和 B.png。

html:

<button>change image src<button>
<img src="A.png">

然后我们通过js修改img src:

document.querySelector('button').onclick = function() {
  document.querySelector('img').src = 'B.png';
}

因为A.png和B.png的大小不同,所以在更改img src时会导致repaint和reflow。

但是如果我们通过css来固定img的大小,如下:

img {
  width: 100px;
  height: 100px;
}

如果我们再次更改img src,是否会导致repaint和reflow?

【问题讨论】:

标签: javascript html css


【解决方案1】:

可能会导致重绘但不会导致回流, Check this Visualization

它发生在我们甚至没有注意到这一切发生的几分之一秒内。

【讨论】:

    【解决方案2】:

    如果你使用的是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>

    【讨论】:

      猜你喜欢
      • 2011-02-19
      • 2017-09-21
      • 2011-07-16
      • 1970-01-01
      • 1970-01-01
      • 2017-01-09
      • 1970-01-01
      • 2019-10-04
      • 2020-09-17
      相关资源
      最近更新 更多