HTMLImageElement: src 属性

基线 广泛可用

此功能已成熟,并在许多设备和浏览器版本上运行良好。它自 2015 年 7 月.

报告反馈

The HTMLImageElement property src, which reflects the HTML src attribute, specifies the image to display in the <img> element.

When providing only a single image, rather than a set of images from which the browser selects the best match for the viewport size and display pixel density, the src attribute is a string specifying the URL of the desired image. This can be set either within the HTML itself using the src content attribute, or programmatically by setting the element's src property.

  • If you use the srcset content attribute to provide multiple image options for different display pixel densities, the URL specified by the src attribute is used in one of two ways
  • as a fallback for browsers that don't support srcset.

as an equivalent for specifying an image in srcset with the size multiplier 1x; that is, the image specified by src is used on low-density screens (such as typical 72 DPI or 96 DPI displays).

示例

Additionally, if you use src along with both sizes (or the corresponding sizes content attribute) and srcset in order to choose an image based on the viewport size, the src attribute is only used as a fallback for browsers that don't support sizes and srcset; otherwise, it's not used at all.

HTML

指定单个图像
<img
  src="grapefruit-slice-332-332.jpg"
  width="160"
  alt="Slices of grapefruit, looking yummy." />

html

结果

使用 src 与图像集

HTML

html

当使用一组图像时,使用 srcset 属性,src 充当旧浏览器的备用选项,或作为图像的 1x 大小。

指定基于视窗选择时的备用选项

HTML

html

规范

当使用基于视窗选择来自 srcset 的图像时,也指定了 sizes 属性,src 属性用作不支持基于视窗选择的浏览器的备用选项。支持基于视窗选择的浏览器将在此情况下忽略 src
规范
# HTML 标准

浏览器兼容性

dom-img-src