在 <picture> 或其 <img> 中设置 `width` 和 `height` 属性有什么作用吗?

Does setting `width` and `height` attributes in <picture> or its <img> do anything?

我想开始在我的网站上使用 WebP。我正在转换如下所示的代码:

<img src="example.jpg" width="100" height="100" alt="Example">

编写如下所示的代码:

<picture>
  <source srcset="example.webp" type="image/webp">
  <img src="example.jpg" width="100" height="100" alt="Example">
</picture>

放置 widthheight 属性的正确位置在哪里?即使选择了 <source> 图像,仅使用 <img> 元素中的 heightwidth 属性是否有效?

是的,在 <img> 元素(而不是其他任何地方)中使用 heightwidth 属性确实可以按预期工作。您无需尝试在 <picture> 元素上设置任何属性。

运行 此代码段用于证明:

<p><code>&lt;img&gt;</code> without <code>height</code> and <code>width</code> attributes:</p>
<picture>
  <source srcset="https://a.webpurr.com/Ql62.webp" type="image/webp">
  <img src="https://i.stack.imgur.com/mraCN.jpg" alt="Example">
</picture>
<p><code>&lt;img&gt;</code> with <code>height</code> and <code>width</code> attributes:</p>
<picture>
  <source srcset="https://a.webpurr.com/Ql62.webp" type="image/webp">
  <img src="https://i.stack.imgur.com/mraCN.jpg" width="100" height="100" alt="Example">
</picture>

(如果您看到标有 "JPEG" 的图片,那么您使用的浏览器不支持 WebP。如果您没有看到图片,可能是图片主机 webpurr.com下来。)