我们知道,更改元素外观时会发生重新绘制,而更改布局时会发生回流。但是,我在更改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时将导致重新绘制和重排。
但是,如果我们通过css固定img的大小,则如下:
img {
width: 100px;
height: 100px;
}
如果再次更改img src,是否会导致重新绘制和重排?
答案 0 :(得分:1)
答案 1 :(得分:1)
如果您使用的是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>