From 074785cea106179cb3305637055ab0a009ca74f2 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:52 -0500 Subject: initial commit --- .../web/api/htmlimageelement/decoding/index.html | 67 ++++ files/ru/web/api/htmlimageelement/image/index.html | 36 +++ files/ru/web/api/htmlimageelement/index.html | 348 +++++++++++++++++++++ .../ru/web/api/htmlimageelement/srcset/index.html | 126 ++++++++ 4 files changed, 577 insertions(+) create mode 100644 files/ru/web/api/htmlimageelement/decoding/index.html create mode 100644 files/ru/web/api/htmlimageelement/image/index.html create mode 100644 files/ru/web/api/htmlimageelement/index.html create mode 100644 files/ru/web/api/htmlimageelement/srcset/index.html (limited to 'files/ru/web/api/htmlimageelement') diff --git a/files/ru/web/api/htmlimageelement/decoding/index.html b/files/ru/web/api/htmlimageelement/decoding/index.html new file mode 100644 index 0000000000..f1c6109bcb --- /dev/null +++ b/files/ru/web/api/htmlimageelement/decoding/index.html @@ -0,0 +1,67 @@ +--- +title: HTMLImageElement.decoding +slug: Web/API/HTMLImageElement/decoding +translation_of: Web/API/HTMLImageElement/decoding +--- +
{{APIRef}}
+ +

Свойство decoding интерфейса {{domxref("HTMLImageElement")}} предназначено для указания браузеру, как он должен декодировать изображение.

+ +

Синтаксис

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

Значения

+ +

{{domxref("DOMString")}} предоствляет указания по декодированию. Возможные значения:

+ +
+
+
    +
  • sync: Декодировать изображение синхронно для отображения одновременно с другим содержимым.
  • +
  • async: Декодировать содержимое асинхронно для уменьшения задержки в отображении другого содержимого.
  • +
  • auto: Режим по умолчанию, который не отдаёт предпочтения ни одному режиму декодирования, предоставляя браузеру решать, какой режим для пользователя оптимальнее.
  • +
+
+
+ +

Примеры

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

Спецификации

+ + + + + + + + + + + + + + + + +
СпецификацияСтатусКоментарий
{{SpecName('HTML WHATWG', 'embedded-content.html#dom-img-decoding', 'decoding')}}{{Spec2('HTML WHATWG')}} 
+ +

Совместимость с браузерами

+ + + +

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

+ +

Смотри также

+ + + +

 

diff --git a/files/ru/web/api/htmlimageelement/image/index.html b/files/ru/web/api/htmlimageelement/image/index.html new file mode 100644 index 0000000000..1c96e0f2d1 --- /dev/null +++ b/files/ru/web/api/htmlimageelement/image/index.html @@ -0,0 +1,36 @@ +--- +title: Image() +slug: Web/API/HTMLImageElement/Image +translation_of: Web/API/HTMLImageElement/Image +--- +
{{ APIRef("HTML DOM") }}
+ +
+ +
Конструктор Image() создает новый экземпляр HTMLImageElement. Эквивалентно document.createElement ('img').
+ +

Конструктор элемента Image

+ +

Имеет два необязательных параметра: ширину и высоту:

+ +
Image([unsigned long width, unsigned long height])
+ +

Пример

+ +
Исходный код:
+ +
var img = new Image(100, 200);
+img.src = 'picture.jpg';
+console.log(img);
+ +
Результат:
+ +
<img width="100" height="200" src="picture.jpg">
+ + + +
+

Примечание: этот конструктор существует только для истории, и возвращает экземпляр HTMLImageElement точно также, как и document.createElement('img').

+
+ +
diff --git a/files/ru/web/api/htmlimageelement/index.html b/files/ru/web/api/htmlimageelement/index.html new file mode 100644 index 0000000000..9aedb53ca9 --- /dev/null +++ b/files/ru/web/api/htmlimageelement/index.html @@ -0,0 +1,348 @@ +--- +title: HTMLImageElement +slug: Web/API/HTMLImageElement +translation_of: Web/API/HTMLImageElement +--- +
{{ApiRef}}
+ +
{{APIRef("HTML DOM")}}
+ +

Интерфейс HTMLImageElement  предоставляет специальные свойства и методы  (расширяя обычный интерфейс {{domxref("HTMLElement")}}  ) для управления вёрсткой и отображением элемента {{HTMLElement("img")}}. 

+ +

{{InheritanceDiagram(600,120)}} 

+ +

Свойства

+ +

Наследует свойства родителя, {{domxref("HTMLElement")}}.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
ИмяТипОписание
align {{obsolete_inline}}{{domxref("DOMString")}}Указывает расположение картинки зависящее от окружающего контента. Возможные значения:  "left""right""justify", и "center".
alt{{domxref("DOMString")}}Повторяет аттрибут HTML {{htmlattrxref("alt", "img")}} указывающий на запасной контекст картинки.
border {{obsolete_inline}}{{domxref("DOMString")}}Ширина рамки вокруг картинки. Устарело и вместо него следует использовать свойство CSS {{cssxref("border")}}.
complete {{readonlyInline}}{{domxref("Boolean")}}Возвращает true, если браузер закончил загрузку картинки с ошибкой или успешно. Также возвращает true, когда не установлено значение  {{domxref("HTMLImageElement.src", "src")}}, во всех остальных случаях - false.
crossOrigin{{domxref("DOMString")}}Является {{domxref("DOMString")}}, с настройками CORS для этого элемента изображения. Дополнительная информация: Атрибуты настроек CORS.  
currentSrc{{readonlyInline}}{{experimental_inline}}{{domxref("DOMString")}}Возвращает {{domxref("DOMString")}} с URL-адресом текущего изображения (что может измениться, например, в ответ на запросы мультимедиа).
heightunsigned longОтражает атрибут {{htmlattrxref ("height", "img")}} HTML, указывая визуализированную высоту изображения в пикселях CSS.
hspace {{obsolete_inline}}longSpace to the left and right of the image.
isMap{{domxref("Boolean")}}Reflects the {{htmlattrxref("ismap", "img")}} HTML attribute, indicating that the image is part of a server-side image map.
longDesc {{obsolete_inline}}{{domxref("DOMString")}}URI of a long description of the image.
lowSrc {{obsolete_inline}}{{domxref("DOMString")}}A reference to a low-quality (but faster to load) copy of the image.
name {{obsolete_inline}}{{domxref("DOMString")}} 
naturalHeight {{readonlyInline}}unsigned longIntrinsic height of the image in CSS pixels, if it is available; otherwise, 0.
naturalWidth {{readonlyInline}}unsigned longIntrinsic width of the image in CSS pixels, if it is available; otherwise, 0.
src{{domxref("DOMString")}}Reflects the {{htmlattrxref("src")}} HTML attribute, containing the URL of the image.
srcset {{experimental_inline}}  
useMap{{domxref("DOMString")}}Reflects the {{htmlattrxref("usemap", "img")}} HTML attribute, containing a partial URL of a map element.
vspace {{obsolete_inline}}longSpace above and below the image.
widthunsigned longReflects the {{htmlattrxref("width", "img")}} HTML attribute, indicating the rendered width of the image in CSS pixels.
x {{readonlyInline}}{{non-standard_inline}}longThe horizontal offset from the nearest layer. (Mimic an old Netscape 4 behavior)
y {{readonlyInline}}{{non-standard_inline}}longThe vertical offset from the nearest layer. (Mimic an old Netscape 4 behavior)
+ +

Методы

+ +

Наследует методы родителя, {{domxref("HTMLElement")}}.

+ +
+
{{domxref("HTMLImageElement.Image()")}}
+
The Image() constructor, taking two optional unsigned long, the width and the height of the resource, creates an instance of HTMLImageElement not inserted in a DOM tree.
+
+ +

Пример

+ +
var img1 = new Image(); // Конструктор HTML5
+img1.src = 'image1.png';
+img1.alt = 'alt';
+document.body.appendChild(img1);
+
+var img2 = document.createElement('img'); // Используем HTMLImageElement
+img2.src = 'image2.jpg';
+img2.alt = 'alt text';
+document.body.appendChild(img2);
+
+// выбираем первое изображение на странице
+alert(document.images[0].src);
+
+ +

Спецификации

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
СпецификацияСтатусКомментарий
{{SpecName('HTML WHATWG', "text-level-semantics.html#the-a-element", "HTMLAnchorElement")}}{{Spec2('HTML WHATWG')}}The following property has been added: srcset.
{{SpecName('HTML5 W3C', "text-level-semantics.html#the-a-element", "HTMLAnchorElement")}}{{Spec2('HTML5 W3C')}}A constructor (with 2 optional parameters) has been added.
+ The following properties are now obsolete: name, border, align, hspace, vspace, and longdesc.
+ The following properties are now unsigned long, instead of long: height, and width.
+ The following properties have been added: crossorigin, naturalWidth, naturalHeight, and complete.
{{SpecName('DOM2 HTML', 'html.html#ID-17701901', 'HTMLImgElement')}}{{Spec2('DOM2 HTML')}}The lowSrc property has been removed.
+ The following properties are now long, instead of DOMString: height, width, hspace, and vspace.
{{SpecName('DOM1', 'level-one-html.html#ID-17701901', 'HTMLImgElement')}}{{Spec2('DOM1')}}Initial definition.
+ +

Совместимость

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
СвойствоChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Общая поддержка{{CompatVersionUnknown}}{{CompatGeckoDesktop(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
lowSrc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
naturalWidth, naturalHeight{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
crossorigin{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
complete{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
srcset{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
x and y{{CompatVersionUnknown}}{{CompatVersionUnknown}} [1]{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
СвойствоAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Общая поддержка{{CompatVersionUnknown}}{{CompatGeckoMobile(1.0)}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
lowSrc{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
naturalWidth, naturalHeight{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
crossorigin{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
complete{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
srcset{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
x and y{{CompatVersionUnknown}}{{CompatVersionUnknown}} [1]{{CompatNo}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

[1] The x and y properties were removed in Gecko 7.0 {{geckoRelease("7.0")}} but restored in Gecko 14.0 {{geckoRelease("14.0")}} for compatibility reasons.

+ +

См. также

+ + diff --git a/files/ru/web/api/htmlimageelement/srcset/index.html b/files/ru/web/api/htmlimageelement/srcset/index.html new file mode 100644 index 0000000000..b4a817c4d3 --- /dev/null +++ b/files/ru/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")}}.

+ +

Свойство srcset, вместе с {{domxref("HTMLImageElement.sizes", "sizes")}}, критически важный атрибут при разработке адаптивных веб-сайтов, ведь они могут использоваться вместе для создания адаптивных страниц, использующих подходящие изображения при определённых условиях.

+ +

Синтаксис

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

Значение

+ +

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.

+ +

Пример

+ +

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);
+
+ +

Результат

+ +

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.

+ +

Спецификации

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

Браузерная поддержка

+ + + +

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

+ +

See also

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