From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../web/api/htmlimageelement/complete/index.html | 90 +++++++++++ .../web/api/htmlimageelement/decode/index.html | 68 +++++++++ .../web/api/htmlimageelement/decoding/index.html | 63 ++++++++ .../web/api/htmlimageelement/image/index.html | 111 ++++++++++++++ files/zh-cn/web/api/htmlimageelement/index.html | 170 +++++++++++++++++++++ .../web/api/htmlimageelement/loading/index.html | 98 ++++++++++++ .../api/htmlimageelement/referrerpolicy/index.html | 120 +++++++++++++++ .../web/api/htmlimageelement/srcset/index.html | 126 +++++++++++++++ 8 files changed, 846 insertions(+) create mode 100644 files/zh-cn/web/api/htmlimageelement/complete/index.html create mode 100644 files/zh-cn/web/api/htmlimageelement/decode/index.html create mode 100644 files/zh-cn/web/api/htmlimageelement/decoding/index.html create mode 100644 files/zh-cn/web/api/htmlimageelement/image/index.html create mode 100644 files/zh-cn/web/api/htmlimageelement/index.html create mode 100644 files/zh-cn/web/api/htmlimageelement/loading/index.html create mode 100644 files/zh-cn/web/api/htmlimageelement/referrerpolicy/index.html create mode 100644 files/zh-cn/web/api/htmlimageelement/srcset/index.html (limited to 'files/zh-cn/web/api/htmlimageelement') diff --git a/files/zh-cn/web/api/htmlimageelement/complete/index.html b/files/zh-cn/web/api/htmlimageelement/complete/index.html new file mode 100644 index 0000000000..cff31934c9 --- /dev/null +++ b/files/zh-cn/web/api/htmlimageelement/complete/index.html @@ -0,0 +1,90 @@ +--- +title: HTMLImageElement.complete +slug: Web/API/HTMLImageElement/complete +translation_of: Web/API/HTMLImageElement/complete +--- +

{{APIRef("HTML DOM")}}

+ +

{{domxref("HTMLImageElement")}} 的只读属性 complete 是一个布尔值, 表示图片是否完全加载完成。

+ +

语法

+ +
let doneLoading = htmlImageElement.complete;
+ +

+ +

当图片完全加载完成时值为 true ; 否则,值为 false

+ +

以下任意一条为true则认为图片完全加载完成:

+ + + +

It's worth noting that due to the image potentially being received asynchronously, the value of complete may change while your script is running.

+ +

Example

+ +

Consider a photo library app that provides the ability to open images into a lightbox mode for improved viewing as well as editing of the image. These photos may be very large, so you don't want to wait for them to load, so your code uses async/await to load the images in the background.

+ +

But imagine that you have other code that needs to only run when the image has completed loading, such as a command that performs red-eye removal on the image in the lightbox. While ideally this command wouldn't even be executed if the image hasn't fully loaded, for improved reliability you want to check to ensure this is the case.

+ +

So the fixRedEyeCommand() function, which is called by the button that triggers red-eye removal, checks the value of the lightbox image's complete property before attempting to do its work. This is demonstrated in the code below.

+ +
let lightboxElem = document.querySelector("#lightbox");
+let lightboxImgElem = lightboxElem.querySelector("img");
+let lightboxControlsElem = lightboxElem.querySelector(".toolbar");
+
+async function loadImage(url, elem) {
+  return new Promise((resolve, reject) => {
+    elem.onload = () => resolve(elem);
+    elem.onerror = reject;
+    elem.src = src;
+  });
+}
+
+async function lightBox(url) {
+  lightboxElem.style.display = "block";
+  await loadImage("https://somesite.net/huge-image.jpg", lightboxImgElem);
+  lightboxControlsElem.disabled = false;
+}
+
+/* ... */
+
+function fixRedEyeCommand() {
+  if (lightboxElem.style.display === "block" && lightboxImgElem.complete) {
+    fixRedEye(lightboxImgElem);
+  } else {
+    /* can't start doing this until the image is fully loaded */
+  }
+}
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-img-complete', 'HTMLImageElement.complete')}}{{Spec2('HTML DOM')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLImageElement.complete")}}

diff --git a/files/zh-cn/web/api/htmlimageelement/decode/index.html b/files/zh-cn/web/api/htmlimageelement/decode/index.html new file mode 100644 index 0000000000..b04b67a431 --- /dev/null +++ b/files/zh-cn/web/api/htmlimageelement/decode/index.html @@ -0,0 +1,68 @@ +--- +title: HTMLImageElement.decode() +slug: Web/API/HTMLImageElement/decode +translation_of: Web/API/HTMLImageElement/decode +--- +
+

{{APIRef("HTML DOM")}}

+ +

{{domxref("HTMLImageElement")}} 接口的 decode() 方法返回一个当图片解码后可安全用于附加到 DOM 上时 resolves 的 {{jsxref("Promise")}} 对象。 这可用于在将图片附加到一个 DOM 中的元素(或作为一个新元素加入 DOM 中)之前启动加载,所以在将图像添加到 DOM 时可以立即渲染图像。这反过来,防止了将图像加入DOM后图像的加载造成下一帧渲染的延迟。

+
+ +

语法

+ +
var promise = HTMLImageElement.decode();
+ +

参数

+ +

无.

+ +

返回

+ +

一个一旦数据准备好可供使用时resolve的promise对象.

+ +

异常

+ +

{{domxref('DOMException')}} 表示解码图像时出错。

+ +

使用提示

+ +

一个 decode() 的潜在用例:当在加载一个非常大的图片时(例如,一个在线相册),你可以在加载初期提供一个低分辨率的缩略图,之后通过实例化一个 {{domxref("HTMLImageElement")}} 将该图像替换为一个全分辨率图像,设置其 source 为全分辨率图像URL,使用 decode() 获取一旦全分辨率图像准备好被使用时 resolved 的 promise 对象。这时你可以使用当前可用的全分辨率图像替换之前的低分辨率图像。

+ +

例子

+ +

以下例子展示了如何使用 decode() 方法来控制一个图像插入 DOM 的时机。若不使用 {{domxref('Promise')}} 返回方法,你将在图像的 {{event("load")}} 事件处理函数中将图像加入 DOM 中,通过 {{event("error")}} 事件处理函数处理错误。

+ +
const img = new Image();
+img.src = 'nebula.jpg';
+img.decode()
+.then(() => {
+  document.body.appendChild(img);
+})
+.catch((encodingError) => {
+  // Do something with the error.
+})
+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG','#dom-img-decode','decode()')}}{{Spec2('HTML WHATWG')}}Initial definition.
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLImageElement.decode")}}

diff --git a/files/zh-cn/web/api/htmlimageelement/decoding/index.html b/files/zh-cn/web/api/htmlimageelement/decoding/index.html new file mode 100644 index 0000000000..2bffa6f664 --- /dev/null +++ b/files/zh-cn/web/api/htmlimageelement/decoding/index.html @@ -0,0 +1,63 @@ +--- +title: HTMLImageElement.decoding +slug: Web/API/HTMLImageElement/decoding +translation_of: Web/API/HTMLImageElement/decoding +--- +
{{APIRef}}
+ +
{{domxref("HTMLImageElement")}} 接口的 decoding 属性用于告诉浏览器使用何种方式解析图像数据。
+ +

Syntax

+ +
refStr = imgElem.decoding;
+imgElem.decoding = refStr;
+ +

Values

+ +

使用 {{domxref("DOMString")}} 表示解码方式. 可使用以下值:

+ +
+
+
    +
  • sync: 同步解码图像,保证与其他内容一起显示。
  • +
  • async: 异步解码图像,加快显示其他内容。
  • +
  • auto: 默认模式,表示不偏好解码模式。由浏览器决定哪种方式更适合用户。
  • +
+
+
+ +

Usage notes

+ +

decoding 属性使您可以控制是否允许浏览器尝试异步加载图像。如果这样做会引起问题,您可指定值为 sync 禁止异步加载。异步加载对 {{HTMLElement("img")}} 元素很有用,对屏幕外的图像对象可能会更有用。

+ +

Examples

+ +
var img = new Image();
+img.decoding = 'sync';
+img.src = 'img/logo.png';
+
+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', 'embedded-content.html#dom-img-decoding', 'decoding')}}{{Spec2('HTML WHATWG')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLImageElement.decoding")}}

diff --git a/files/zh-cn/web/api/htmlimageelement/image/index.html b/files/zh-cn/web/api/htmlimageelement/image/index.html new file mode 100644 index 0000000000..e4e73b99f9 --- /dev/null +++ b/files/zh-cn/web/api/htmlimageelement/image/index.html @@ -0,0 +1,111 @@ +--- +title: Image() +slug: Web/API/HTMLImageElement/Image +tags: + - 图片对象 +translation_of: Web/API/HTMLImageElement/Image +--- +
{{ APIRef("HTML DOM") }}
+ +

Image()函数将会创建一个新的{{domxref("HTMLImageElement")}}实例。

+ +

它的功能等价于 {{domxref("Document.createElement()", "document.createElement('img')")}}

+ +

语法

+ +
Image(width, height)
+ +

参数

+ +
+
width
+
图片的宽度 (即 {{htmlattrxref("width", "img")}} 属性).
+
height
+
图片的高度 (即 {{htmlattrxref("height", "img")}} 属性).
+
+ +

示例

+ +
var myImage = new Image(100, 200);
+myImage.src = 'picture.jpg';
+document.body.appendChild(myImage);
+ +
上面的代码相当于在 {{htmlelement("body")}}中定义了下面的HTML:
+ +
<img width="100" height="200" src="picture.jpg">
+
+ +
+

Note: 无论构造函数中指定的大小是多少,都会加载整个位图. 如果在构造时指定了尺寸信息,那么将会反应在实例的 {{domxref("HTMLImageElement.width")}} 和 {{domxref("HTMLImageElement.height")}} 属性上。图像自身的CSS像素值将会反应在{{domxref("HTMLImageElement.naturalWidth")}} 和 {{domxref("HTMLImageElement.naturalHeight")}}属性。如果没有指定值,那么两个属性的值相同

+
+ +

规范

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "embedded-content.html#dom-image", "Image()")}}{{spec2("HTML WHATWG")}} 
+ +

兼容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
支持情况{{compatversionunknown}}{{compatversionunknown}}{{compatversionunknown}}{{compatversionunknown}}{{compatversionunknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
支持情况{{compatversionunknown}}{{compatversionunknown}}{{compatversionunknown}}{{compatversionunknown}}{{compatversionunknown}}{{compatversionunknown}}{{compatversionunknown}}
+
diff --git a/files/zh-cn/web/api/htmlimageelement/index.html b/files/zh-cn/web/api/htmlimageelement/index.html new file mode 100644 index 0000000000..19ae9dd455 --- /dev/null +++ b/files/zh-cn/web/api/htmlimageelement/index.html @@ -0,0 +1,170 @@ +--- +title: HTMLImageElement +slug: Web/API/HTMLImageElement +translation_of: Web/API/HTMLImageElement +--- +
{{ APIRef("HTML DOM") }}
+ +

HTMLImageElement 接口提供了特别的属性和方法 (在常规的 {{domxref("HTMLElement")}}之外,它也能通过继承使用)来操纵 {{HTMLElement("img")}} 元素的布局和图像。

+ +

{{InheritanceDiagram(600, 120)}}

+ +

Constructor

+ +
+
{{domxref("HTMLImageElement.Image()", "Image()")}}
+
Image() 构造器,带有两个可选的参数,分别表示资源的宽度和高度,创建了一个尚未被插入 DOM 树中的 HTMLImageElement 实例。When called without parameters, new Image() is equivalent to calling {{DOMxRef("Document.createElement()", 'document.createElement("img")')}}.
+
+ +

属性

+ +

从它的父元素 {{domxref("HTMLElement")}} 继承的属性。

+ +
+
{{domxref("HTMLImageElement.alt")}}
+
一个 {{domxref("DOMString")}} 表示 HTML 属性 {{htmlattrxref("alt", "img")}},表明图像的后备描述内容,会在图像无法加载时显示。
+
{{domxref("HTMLImageElement.complete")}} {{readonlyInline}}
+
返回一个 {{domxref("Boolean")}} 如果浏览器已经下载完毕,并且图像是受支持的图片类型、解码的过程中没有发生错误,则返回 true。That means this value is also true if the image has no {{domxref("HTMLImageElement.src", "src")}} value indicating an image to load.
+
{{domxref("HTMLImageElement.crossOrigin")}}
+
一个 {{domxref("DOMString")}} 表示这个img元素的 CORS 设置。参考 CORS settings attributes。This may be null if CORS is not used.
+
{{domxref("HTMLImageElement.currentSrc")}} {{readonlyInline}}
+
返回一个 {{domxref("DOMString")}}  表示加载当前显示的图像的URL。
+ 这可能会改变,因为图像是调整,由于不断变化的条件,由任何 media queries 的地方。
+
{{domxref("HTMLImageElement.decoding")}}
+
An optional {{domxref("DOMString")}} representing a hint given to the browser on how it should decode the image. If this value is provided, it must be one of the possible permitted values: sync to decode the image synchronously, async to decode it asynchronously, or auto to indicate no preference (which is the default). Read the {{domxref("HTMLImageElement.decoding", "decoding")}} page for details on the implications of this property's values.
+
{{domxref("HTMLImageElement.height")}}
+
一个整数,表示 HTML 属性 {{htmlattrxref("height", "img")}},说明了图像在 CSS 像素中渲染的高度。
+
{{domxref("HTMLImageElement.isMap")}}
+
一个 {{domxref("Boolean")}} 表示 HTML 属性 {{htmlattrxref("ismap", "img")}},说明了图像是某个服务器端图像映射的一部分。This is different from a client-side image map, specified using an <img> element and a corresponding {{HTMLElement("map")}} which contains {{HTMLElement("area")}} elements indicating the clickable areas in the image. The image must be contained within an {{HTMLElement("a")}} element; see the ismap page for details.
+
{{domxref("HTMLImageElement.naturalHeight")}} {{readonlyInline}}
+
返回一个整数,如果可用的话,表明图像在 CSS 中固有的高度,单位为像素;否则返回 0。如果图片是以其原来的大小渲染,则此值等于图片的高度。
+
{{domxref("HTMLImageElement.naturalWidth")}} {{readonlyInline}}
+
返回一个整数,如果可用的话,表明图像在 CSS 中固有的宽度,单位为像素;否则返回 0。如果图片是以其原来的大小渲染,则此值等于图片的宽度。
+
{{domxref("HTMLImageElement.referrerPolicy")}}
+
A {{domxref("DOMString")}} that reflects the {{htmlattrxref("referrerpolicy", "img")}} HTML attribute, which tells the {{Glossary("user agent")}} how to decide which referrer to use in order to fetch the image. Read this article for details on the possible values of this string.
+
{{domxref("HTMLImageElement.sizes")}} {{experimental_inline}}
+
A {{domxref("DOMString")}} reflecting the {{htmlattrxref("sizes", "img")}} HTML attribute. This string specifies a list of comma-separated conditional sizes for the image; that is, for a given viewport size, a particular image size is to be used. Read the documentation on the {{domxref("HTMLImageElement.sizes", "sizes")}} page for details on the format of this string.
+
{{domxref("HTMLImageElement.src")}}
+
一个 {{domxref("DOMString")}} 表示 HTML 属性 {{htmlattrxref("src", "img")}},包含图像的完整的 URL,包含图像的基础 URL。
+
{{domxref("HTMLImageElement.srcset")}} {{experimental_inline}}
+
一个 {{domxref("DOMString")}} 表示 HTML 属性 {{htmlattrxref("srcset", "img")}},包含了候选图像列表,用逗号分隔(',', U+002C COMMA)。一个候选的图像是一个URL 跟着一个 'w' 表示图像的宽度,或者一个 'x' 表示像素密度.
+
{{domxref("HTMLImageElement.useMap")}}
+
一个 {{domxref("DOMString")}} 表示 HTML 属性 {{htmlattrxref("usemap", "img")}},包含一个 {{HTMLElement("map")}} 元素的页面本地 URL。The page-local URL is a pound (hash) symbol (#) followed by the ID of the <map> element, such as #my-map-element. The <map> in turn contains {{HTMLElement("area")}} elements indicating the clickable areas in the image.
+
{{domxref("HTMLImageElement.width")}}
+
一个整数,表示 HTML 属性 {{htmlattrxref("width", "img")}},说明图像在 CSS 像素中渲染的宽度。
+
{{domxref("HTMLImageElement.x")}} {{readonlyInline}}{{experimental_inline}}
+
An integer indicating the horizontal offset of the left border edge of the image's CSS layout box relative to the origin of the {{HTMLElement("html")}} element's containing block.
+
{{domxref("HTMLImageElement.y")}} {{readonlyInline}} {{experimental_inline}}
+
The integer vertical offset of the top border edge of the image's CSS layout box relative to the origin of the {{HTMLElement("html")}} element's containing block.
+
+ +

已废弃的属性

+ +
+
{{domxref("HTMLImageElement.align")}} {{obsolete_inline}}
+
一个 {{domxref("DOMString")}},表示图像如何与它周围的内容对齐。The possible values are "left", "right", "justify", and "center". This is obsolete; you should instead use CSS (such as {{cssxref("text-align")}}, which works with images despite its name) to specify the alignment.
+
{{domxref("HTMLImageElement.border")}} {{obsolete_inline}}
+
一个 {{domxref("DOMString")}},表示图像边框的宽度。此属性已被弃用,应该用 CSS {{cssxref("border")}} 属性来代替它。
+
{{domxref("HTMLImageElement.hspace")}} {{obsolete_inline}}
+
一个整数值,指定图像左右的留白,单位为像素。
+
{{domxref("HTMLImageElement.longDesc")}} {{obsolete_inline}}
+
一个 {{domxref("USVString")}},specifying the URL at which a long description of the image's contents may be found. This is used to turn the image into a hyperlink automatically. Modern HTML should instead simply place an <img> inside an {{HTMLElement("a")}} element defining the hyperlink.
+
{{domxref("HTMLImageElement.lowSrc")}} {{obsolete_inline}}
+
一个 {{domxref("USVString")}},specifying the URL of a low-quality (but faster to load) version of the same image. This was once used by browsers under constrained network conditions or on slow devices.
+
{{domxref("HTMLImageElement.name")}} {{obsolete_inline}}
+
一个 {{domxref("DOMString")}},representing the name of the element.
+
{{domxref("HTMLImageElement.vspace")}} {{obsolete_inline}}
+
一个整数值,指定图像上下的留白,单位为像素。
+
+ +

方法

+ +

从它的父元素 {{domxref("HTMLElement")}} 继承的方法。

+ +
+
{{domxref("HTMLImageElement.decode()")}}
+
Returns a {{jsxref("Promise")}} that resolves when the image is decoded and it's safe to append the image to the DOM. This prevents rendering of the next frame from having to pause to decode the image, as would happen if an undecoded image were added to the DOM.
+
+ +

错误

+ + + +
+
If an error occurs while trying to load or render the image, and an {{htmlattrxref("onerror")}} event handler has been configured to handle the {{event("error")}} event, that event handler will get called. This can happen in a number of situations, including:
+
+ +

例子

+ +
var img1 = new Image(); // Image 构造器
+img1.src = 'image1.png';
+img1.alt = 'alt';
+document.body.appendChild(img1);
+
+var img2 = document.createElement('img'); // 使用 DOM HTMLImageElement
+img2.src = 'image2.jpg';
+img2.alt = 'alt text';
+document.body.appendChild(img2);
+
+// 使用文档中的第一个 img
+alert(document.images[0].src);
+
+ +

规范

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
规范状态备注
{{SpecName("CSSOM View", "#excensions-to-the-htmlimageelement-interface", "Extensions to HTMLImageElement")}}{{Spec2('CSSOM View')}}添加 xy 属性。
{{SpecName('HTML WHATWG', "embedded-content.html#the-img-element", "HTMLImageElement")}}{{Spec2('HTML WHATWG')}}以下属性被添加了:srcsetcurrentSrcsizes
{{SpecName('HTML5 W3C', "embedded-content-0.html#the-img-element", "HTMLImageElement")}}{{Spec2('HTML5 W3C')}}一个构造器(带有 2 个可选的参数)已经被添加.
+ 以下属性已被弃用:nameborderalignhspacevspace,和 longdesc.
+ 以下属性现在是 unsigned long, 类型,不再是 long 类型: heightwidth
+ 添加了以下属性:crossorigin, naturalWidth, naturalHeight, 和complete.
{{SpecName('DOM2 HTML', 'html.html#ID-17701901', 'HTMLImgElement')}}{{Spec2('DOM2 HTML')}}The lowSrc 属性已被移除。
+ 以下属性现在是 long 类型了,而不是 DOMString 类型了: heightwidthhspace,和 vspace
{{SpecName('DOM1', 'level-one-html.html#ID-17701901', 'HTMLImgElement')}}{{Spec2('DOM1')}}初始定义。
+ +

浏览器兼容性

+ + + +

{{Compat("api.HTMLImageElement")}}

+ +

参见

+ + diff --git a/files/zh-cn/web/api/htmlimageelement/loading/index.html b/files/zh-cn/web/api/htmlimageelement/loading/index.html new file mode 100644 index 0000000000..9566b4a7c1 --- /dev/null +++ b/files/zh-cn/web/api/htmlimageelement/loading/index.html @@ -0,0 +1,98 @@ +--- +title: HTMLImageElement.loading +slug: Web/API/HTMLImageElement/loading +tags: + - 懒加载 +translation_of: Web/API/HTMLImageElement/loading +--- +

{{APIRef("HTML DOM")}}

+ +

{{domxref("HTMLImageElement")}} 的loading属性为一个字符串,它的值会提示 {{Glossary("用户代理")}} 告诉浏览器不在{{Glossary("可视视口")}}内的图片该如何加载。这样一来,通过推迟图片加载仅让其在需要的时候加载而非页面初始载入时立刻加载,优化了页面的载入。 

+ +

语法

+ +
let imageLoadScheduling = htmlImageElement.loading;
+htmlImageElement.loading = eagerOrLazy;
+
+ +

+ +

{{domxref("DOMString")}} 提示用户代理该如何最佳规划图片加载来优化页面性能。可能的值有:

+ +
+
eager
+
默认行为, eager 告诉浏览器当处理 <img> 标签时立即加载图片。
+
lazy
+
告诉用户代理推迟图片加载直到浏览器认为其需要立即加载时才去加载。例如,如果用户正在往下滚动页面,值为 lazy 会导致图片仅在马上要出现在 {{Glossary("可视视口")}}中时开始加载.
+
+ +

使用说明

+ +

load事件的时机

+ +

  {{domxref("Window.load_event","load")}} 事件在文档被完整的处理完成时触发。当图片使用立即加载(默认值)时,文档中的所有图片都会在 load 事件触发前载入。

+ +

当 loading 值设为 lazy 时,图片不再会在请求,下载,处理的时间内推迟 load 事件触发。

+ +

 loading 属性值设为 lazy 但是在页面初次加载时就在可视视口内的图片会立即加载但它们也不会推迟 load 事件。换句话说,这些图片不会在处理  <img> 元素时立即加载,但仍会作为页面初始加载的一部分而加载。他们只是不会影响 load 事件。

+ +

这表明当 load 触发时,可视区域内懒加载的图片可能不可见。

+ +

防止元素在图片懒加载时出现移位

+ +

当一个加载被 loading 属性设为 lazy 的图片最后加载时,浏览器会根据{{HTMLElement("img")}} 元素的尺寸和图片自身大小重排文档,更新被图片影响的元素的位置。

+ +

为了防止重排发生,你需要使用 {{htmlattrxref("width", "img")}} 和 {{htmlattrxref("height", "img")}} 属性明确设置图片大小。通过这样建立固有长宽比,你防止了元素的移位。取决于实际的加载时间和重排,移位造成的最小的影响可能只是使用户困惑和不适,最坏的影响则是导致用户点错目标。

+ +

示例

+ +

下面展示的 addImageToList() 函数将一个照片缩略图添加到一个物品列表中,使用懒加载防止请求图片,直到其真正需要显示。

+ +
function addImageToList(url) {
+  const list = document.querySelector("div.photo-list");
+
+  let newItem = document.createElement("div");
+  newItem.className = "photo-item";
+
+  let newImg = document.createElement("img");
+  newImg.loading = "lazy";
+  newImg.width = 320;
+  newImg.height = 240;
+  newImg.src = url;
+
+  newItem.appendChild(newImg);
+  list.appendChild(newItem);
+}
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', "#attr-img-loading", "HTMLImageElement.loading")}}{{Spec2('HTML WHATWG')}}
+ +

浏览器兼容

+ +

{{Compat("api.HTMLImageElement.loading")}}

+ +

相关链接

+ + diff --git a/files/zh-cn/web/api/htmlimageelement/referrerpolicy/index.html b/files/zh-cn/web/api/htmlimageelement/referrerpolicy/index.html new file mode 100644 index 0000000000..c670d136f3 --- /dev/null +++ b/files/zh-cn/web/api/htmlimageelement/referrerpolicy/index.html @@ -0,0 +1,120 @@ +--- +title: HTMLImageElement.referrerPolicy +slug: Web/API/HTMLImageElement/referrerPolicy +translation_of: Web/API/HTMLImageElement/referrerPolicy +--- +
{{APIRef}}{{SeeCompatTable}}
+ + + +

HTMLImageElement.referrerPolicy 反映了 {{HTMLElement("img")}} 元素的HTML属性 {{htmlattrxref("referrerpolicy","img")}} 的定义,这个属性定义了{{HTMLElement("img")}} 元素在获取资源时的引用方式。

+ + + +

语法

+ +
refStr = imgElt.referrerPolicy;
+imgElt.referrerPolicy = refStr;
+ +

+ +
+
+
    +
  • "no-referrer" 表示HTTP头部信息将不会发送 referrer
  • +
  • "origin" 表示 referrer 只包含策略、主机名、端口等页面源的信息。
  • +
  • "unsafe-url" 这意味着引用者将包括源站和路径(但不包括片段、密码或用户名)。这种情况是不安全的,因为它可能会泄漏路径信息,这些信息已被使用TLS隐藏到第三方。
  • +
+
+
+ +

例子

+ +
var img = new Image();
+img.src = 'img/logo.png';
+img.referrerPolicy = 'origin';
+
+var div = document.getElementById('divAround');
+div.appendChild(img); // Fetch the image using the origin as the referrer
+
+ +

规范

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Referrer Policy', '#referrer-policy-delivery-referrer-attribute', 'referrerPolicy attribute')}}{{Spec2('Referrer Policy')}}Added the referrerPolicy property.
+ +

浏览器兼容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome("51")}}{{CompatUnknown}}{{CompatGeckoDesktop("50.0")}} [1]{{CompatUnknown}}{{CompatOpera("38")}}{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
FeatureAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{CompatChrome("51")}}{{CompatChrome("51")}}{{CompatGeckoMobile("50.0")}} [1]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] 从火狐45到50,这都是在network.http.enableperelementerfer首选项之后。从火狐42到44,这个属性被称为referer。

+ +

相关

+ + diff --git a/files/zh-cn/web/api/htmlimageelement/srcset/index.html b/files/zh-cn/web/api/htmlimageelement/srcset/index.html new file mode 100644 index 0000000000..9e100502ee --- /dev/null +++ b/files/zh-cn/web/api/htmlimageelement/srcset/index.html @@ -0,0 +1,126 @@ +--- +title: HTMLImageElement.srcset +slug: Web/API/HTMLImageElement/srcset +translation_of: Web/API/HTMLImageElement/srcset +--- +

{{APIRef("HTML DOM")}}

+ +

{{domxref("HTMLImageElement")}} 的 srcset 的值是一个字符串,用来定义一个或多个图像候选地址,以 ,分割,每个候选地址将在特定条件下得以使用。候选地址包含图片 URL 和一个可选的宽度描述符和像素密度描述符,该候选地址用来在特定条件下替代原始地址成为 {{domxref("HTMLImageElement.src", "src")}}  的属性。

+ +

The srcset property, along with the {{domxref("HTMLImageElement.sizes", "sizes")}} property, are a crucial component in designing responsive web sites, as they can be used together to make pages that use appropriate images for the rendering situation.

+ +

Syntax

+ +
htmlImageElement.srcset = imageCandidateStrings;
+let srcset = htmlImageElement.srcset;
+
+ +

Value

+ +

A {{domxref("USVString")}} containing a comma-separated list of one or more image candidate strings to be used when determining which image resource to present inside the {{HTMLElement("img")}} element represented by the HTMLImageElement.

+ +

Each image candidate string must begin with a valid URL referencing a non-interactive graphic resource. This is followed by a comma (,) character and then a condition descriptor that indicates the circumstances in which the indicated image should be used. Space characters, other than the whitespace separating the URL and the corresponding condition descriptor, are ignored; this includes both leading and trailing space, as well as space before or after each comma.

+ +

If the condition descriptor is not provided (in other words, the image candidate provides only a URL), the candidate is used as the fallback if none of the other candidates match. Otherwise, the condition descriptor may take one of two forms:

+ + + +

You may mix and match the two types of descriptor. You must not, however, provide multiple image candidate strings that specify the same descriptor. All of the following are valid image candidate strings:

+ +
"images/team-photo.jpg 1x, images/team-photo-retina.jpg 2x, images/team-photo-full 2048w"
+ +

This string provides versions of an image to be used at the standard pixel density (1x) as well as double that pixel density (2x). Also available is a version of the image for use at a width of 2048 pixels (2048w).

+ +
"header640.png 640w, header960.png 960w, header1024.png 1024w, header.png"
+ +

This string provides versions of a header image to use when the {{Glossary("user agent", "user agent's")}} renderer needs an image of width 640px, 960px, or 1024px. An additional, fallback image candidate is provided without any condition at all, to be used for any other width.

+ +
"icon32px.png 32w, icon64px.png 64w, icon-retina.png 2x icon-ultra.png 3x icon.svg"
+ +

Here, options are provided for an icon at widths of 32px and 64px, as well as at pixel densities of 2x and 3x. A fallback image is provided as an SVG file that should be used in all other cases. Notice that the candidates may use different image types.

+ +

For more information on what image formats are available for use in the {{HTMLElement("img")}} element, see Image file type and format guide.

+ +

Example

+ +

HTML

+ +

The HTML below indicates that the default image is the 200 pixel wide version of the clock image we use in several places throughout our documentation. Also specified by the srcset attribute is that the 200-pixel version should be used for 1x displays while the 400-pixel version should be used for 2x displays.

+ +
<div class="box">
+  <img src="/files/16797/clock-demo-200px.png"
+       alt="Clock"
+       srcset="/files/16864/clock-demo-200px.png 1x, /files/16797/clock-demo-400px.png 2x">
+</div>
+
+ +

CSS

+ +

The CSS simply specifies that the image and its surrounding box should be 200 pixels square and should have a simple border around it. Also provided is the {{cssxref("word-break")}} attribute, using the break-all value to tell the browser to wrap the string within the width available regardless of where in the string the wrap must occur.

+ +
.box {
+  width: 200px;
+  border: 2px solid rgba(150, 150, 150, 255);
+  padding: 0.5em;
+  word-break: break-all;
+}
+
+.box img {
+  width: 200px;
+}
+ +

JavaScript

+ +

The following code is run within a handler for the {{domxref("Window", "window")}}'s {{domxref("Window.load_event", "load")}} event.  It uses the image's  {{domxref("HTMLImageElement.currentSrc", "currentSrc")}} property to fetch and display the URL selected by the browser from the srcset.

+ +
let box = document.querySelector(".box");
+let image = box.querySelector("img");
+
+let newElem = document.createElement("p");
+newElem.innerHTML = `Image: <code>${image.currentSrc}</code>`;
+box.appendChild(newElem);
+
+ +

Result

+ +

In the displayed output below, the selected URL will correspond with whether your display results in selecting the 1x or the 2x version of the image. If you happen to have both standard and high density displays, try moving this window between them and reloading the page to see the results change.

+ +

{{EmbedLiveSample("Example", 640, 320)}}

+ +

For additional examples, see our guide to responsive images.

+ +

Specifications

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('HTML WHATWG', '#dom-img-srcset', 'HTMLImageElement.srcset')}}{{Spec2('HTML WHATWG')}}
+ +

Browser compatibility

+ + + +

{{Compat("api.HTMLImageElement.srcset")}}

+ +

See also

+ + -- cgit v1.2.3-54-g00ecf