HTMLImageElement.src - Web APIs 编辑

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

Syntax

htmlImageElement.src = newSource;
let src = htmlImageElement.src;

Value

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 USVString 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.

Examples

Specifying a single image

HTML

<img src="https://interactive-examples.mdn.mozilla.net/media/examples/grapefruit-slice-332-332.jpg"
     width="160"
     alt="Slices of grapefruit, looking yummy.">

Result

Using src with an image set

When using a set of images with the srcset property, the src serves as either a fallback for older browsers, or as the 1x size of the image.

HTML

Result

Specifying a fallback for viewport-based selection

When using viewport-bases selection of an image from a srcset by also specifying the sizes property, the src property serves as the fallback to be used on browsers that don't support viewport-based selection. Browsers that do support viewport-based selection will ignore src in this situation.

HTML

Result

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'HTMLImageElement.src' in that specification.
Living Standard

Browser compatibility

BCD tables only load in the browser

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:41 次

字数:5162

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文