HTMLSourceElement: width 属性

HTMLSourceElement 接口的 width 属性是一个非负数,表示图像资源的 CSS 像素宽度。

该属性仅在当前 <source> 元素的父元素是 <picture> 元素时才生效。

它反映了 <source> 元素的 width 属性。

一个非负数,表示图像资源的 CSS 像素宽度。

示例

html
<picture id="img">
  <source
    srcset="landscape.png"
    media="(width >= 1000px)"
    width="1000"
    height="400" />
  <source
    srcset="square.png"
    media="(width >= 800px)"
    width="800"
    height="800" />
  <source
    srcset="portrait.png"
    media="(width >= 600px)"
    width="600"
    height="800" />
  <img
    src="fallback.png"
    alt="Image used when the browser does not support the sources"
    width="500"
    height="400" />
</picture>
js
const img = document.getElementById("img");
const sources = img.querySelectorAll("source");
console.log(Array.from(sources).map((el) => el.width)); // Output: [1000, 800, 600]

规范

规范
HTML
# dom-dim-width

浏览器兼容性

另见