From 95aca4b4d8fa62815d4bd412fff1a364f842814a Mon Sep 17 00:00:00 2001 From: Ryan Johnson Date: Thu, 29 Apr 2021 16:16:42 -0700 Subject: remove retired locales (#699) --- .../web/api/intersection_observer_api/index.html | 610 --------------------- 1 file changed, 610 deletions(-) delete mode 100644 files/uk/web/api/intersection_observer_api/index.html (limited to 'files/uk/web/api/intersection_observer_api') diff --git a/files/uk/web/api/intersection_observer_api/index.html b/files/uk/web/api/intersection_observer_api/index.html deleted file mode 100644 index 49a9ce1d06..0000000000 --- a/files/uk/web/api/intersection_observer_api/index.html +++ /dev/null @@ -1,610 +0,0 @@ ---- -title: Intersection Observer API -slug: Web/API/Intersection_Observer_API -tags: - - API - - Clipping - - Intersection - - Intersection Observer API - - IntersectionObserver - - Overview - - Performance - - Reference - - Web - - Швидкодія -translation_of: Web/API/Intersection_Observer_API ---- -
{{DefaultAPISidebar("Intersection Observer API")}}
- -

Intersection Observer API дозволяє веб-застосункам асинхронно стежити за зміною перетину елемента з його батьком чи областю видимості документа {{Glossary("viewport")}}.

- -

Історично склалося так, що виявлення видимості окремого елемента чи видимості двох елементів по відношенню один до одного було непростою задачею. Варіанти вирішення цієї задачі були ненадійними і сповільнювали роботу браузера. На жаль, з "дорослішанням" вебу, необхідність у вирішенні цієї проблеми тільки зростала, з різних причин, таких як:

- - - -

Раніше реалізація виявлення пересічення елементів означала використання обробників подій і циклів, викликаючих методи типу {{domxref("Element.getBoundingClientRect()")}}, щоб зібрати необхідну інформацію про кожен зачеплений елемент. Оскільки весь цей код працює в основному потоці, виникають проблеми з продуктивністю.

- -

Розглянемо веб-сторінку з безкінечним скролом. На сторінці використовується бібліотека для керування періодично розміщуваною по всій сторінці рекламою, всюди анімована графіка, а також бібліотека для відображення спливаючих вікон. І всі ці речі використовують свої власні правила для визначення перетинів, і всі вони запущені в основному потоці. Автор сайту може навіть не підозрювати про цю проблему, а також може не знати, як працюють сторонні бібліотеки зсередини. В той же час користувач по ходу прокрутки сторінки стикається з тим, що робота сайта сповільнюється постійним спрацьовуванням виявлення перетинів, що в підсумку призводить до того, що користувач не задоволений браузером, сайтом і своїм комп'ютером.

- -

Intersection Observer API дає можливість зареєструвати callback-функцію, яка виконається при перетині спостережуваним елементом кордонів іншого елемента (чи області видимості документа {{Glossary("viewport")}}), або при зміні величини перетину на визначене значення. Таким чином, більше немає необхідності вираховувати перетин елементів в основному потоці, і браузер може оптимізовувати ці процеси на свій погляд.

- -

Observer API не дозволить дізнатися точне число пікселів чи визначати конкретні пікселі в перетині; проте, його використання покриває найбільш поширені випадки, наприклад "Якщо елементи перетинаються на N%, зроби це і це".

- -

Основні поняття і використання Intersection Observer API 

- -

Intersection Observer API дозволяє вказати функцію, яка буде викликана щоразу для елемента (target) при перетині його з областю видимості документа (по-замовчуванню) чи заданим елементом (root).

- -

Зазвичай, використовується відстеження перетину елементу з областю видимості (необхідно вказати  null в якості кореневого елементу).

- -

Чи використовуємо ми область видимості чи інший елемент в якості кореневого, API працює однаково, викликаючи задану вами функцію зворотнього виклику, щоразу, коли видимість цільового елементу змінюється так, що вона перетинає в потрібному ступені кореневий елемент.

- -

Ступінь перетину цільового і кореневого елементу задається в діапазоні від 0.0 до 1.0, де 1.0 це повний перетин цільовим елементом кордонів кореневого.

- -

Створення intersection observer

- -

Для початку з допомогою конструктору потрібно створити об'єкт-спостерігач, вказати для нього функцію для виклику і налаштування відстеження:

- -
let options = {
-  root: document.querySelector('#scrollArea'),
-  rootMargin: '0px',
-  threshold: 1.0
-}
-
-let observer = new IntersectionObserver(callback, options);
-
- -

Параметр threshold зі значенням 1.0 означає що функція буде викликана при 100% перетину об'єкта (за яким ми стежимо) з об'єктом root.

- -

Налаштування Intersection observer

- -

The options object passed into the {{domxref("IntersectionObserver.IntersectionObserver", "IntersectionObserver()")}} constructor let you control the circumstances under which the observer's callback is invoked. It has the following fields:

- -
-
root
-
Елемент який використовується в якості області перегляду для перевірки видимості цільового елементу. Повинен бути батьком цільового елементу. По замовчуванню використовується область видимості браузера якщо не визначений або має значення  null.
-
rootMargin
-
-

Відступи навколо root. Можуть мати значення як властивість css margin: 10px 20px 30px 40px" (top, right, bottom, left). Значення можна задавати у відсотках. По замовчуванню всі параметри встановлені в нулі.

-
-
threshold
-
Число чи масив чисел, який вказує, при якому відсотку видимості цільового елементу повинен спрацювати callback. Наприклад, в цьому випадку callback функція буде викликатися при появі в зоні видимості кожні 25% цільового елементу: [0, 0.25, 0.5, 0.75, 1]. Дефолтне значення 0 (як тільки хоча б один піксель стане видимим, то буде викликаний колбек). Значення 1.0 означає, що увесь елемент повністю має стати видимим перед тим, як буде викликано колбек.
-
- -

Цільовий елемент, який буде спостерігатися

- -

Після того, як ви створили спостерігача, вам потрібно дати йому цільовий елемент для перегляду:

- -
let target = document.querySelector('#listItem');
-observer.observe(target);
-
-// the callback we setup for the observer will be executed now for the first time
-// it waits until we assign a target to our observer (even if the target is currently not visible)
-
- -

Щоразу, коли ціль досягає порогового значення, вказаного для IntersectionObserver, викликається функція зворотнього виклику callback. Де callback отримує список об'єктів IntersectionObserverEntry і спостерігача:

- -
let callback = (entries, observer) => {
-  entries.forEach(entry => {
-    // Each entry describes an intersection change for one observed
-    // target element:
-    //   entry.boundingClientRect
-    //   entry.intersectionRatio
-    //   entry.intersectionRect
-    //   entry.isIntersecting
-    //   entry.rootBounds
-    //   entry.target
-    //   entry.time
-  });
-};
-
- -

Зверніть увагу, що функція зворотнього виклику запускається в головному потоці і повинна виконуватися якнайшвидше, тому якщо щось забирає багато часу, то використовуйте {{domxref("Window.requestIdleCallback()")}}.

- -

Також зверніть увагу, що якщо ви вказали опцію root, цільовий елемент повинен бути потомком кореневого елементу. 

- -

How intersection is calculated

- -

All areas considered by the Intersection Observer API are rectangles; elements which are irregularly shaped are considered as occupying the smallest rectangle which encloses all of the element's parts. Similarly, if the visible portion of an element is not rectangular, the element's intersection rectangle is construed to be the smallest rectangle that contains all the visible portions of the element.

- -

It's useful to understand a bit about how the various properties provided by {{domxref("IntersectionObserverEntry")}} describe an intersection.

- -

The intersection root and root margin

- -

Before we can track the intersection of an element with a container, we need to know what that container is. That container is the intersection root, or root element. This can be either a specific element in the document which is an ancestor of the element to be observed, or null to use the document's viewport as the container.

- -

The root intersection rectangle is the rectangle used to check against the target or targets. This rectangle is determined like this:

- - - -

The root intersection rectangle can be adjusted further by setting the root margin, rootMargin, when creating the {{domxref("IntersectionObserver")}}. The values in rootMargin define offsets added to each side of the intersection root's bounding box to create the final intersection root bounds (which are disclosed in {{domxref("IntersectionObserverEntry.rootBounds")}} when the callback is executed).

- -

Thresholds

- -

Rather than reporting every infinitesimal change in how much a target element is visible, the Intersection Observer API uses thresholds. When you create an observer, you can provide one or more numeric values representing percentages of the target element which are visible. Then, the API only reports changes to visibility which cross these thresholds.

- -

For example, if you want to be informed every time a target's visibility passes backward or forward through each 25% mark, you would specify the array [0, 0.25, 0.5, 0.75, 1] as the list of thresholds when creating the observer. You can tell which direction the visibility changed in (that is, whether the element became more visible or less visible) by checking the value of the {{domxref("IntersectionObserverEntry.isIntersecting", "isIntersecting")}} property on the {{domxref("IntersectionObserverEntry")}} passed into the callback function at the time of the visibility change. If isIntersecting is true, the target element has become at least as visible as the threshold that was passed. If it's false, the target is no longer as visible as the given threshold.

- -

To get a feeling for how thresholds work, try scrolling the box below around. Each colored box within it displays the percentage of itself that's visible in all four of its corners, so you can see these ratios change over time as you scroll the container. Each box has a different set of thresholds:

- - - - - -

{{EmbedLiveSample("Threshold_example", 500, 500)}}

- -

Clipping and the intersection rectangle

- -

The browser computes the final intersection rectangle as follows; this is all done for you, but it can be helpful to understand these steps in order to better grasp exactly when intersections will occur.

- -
    -
  1. The target element's bounding rectangle (that is, the smallest rectangle that fully encloses the bounding boxes of every component that makes up the element) is obtained by calling {{domxref("Element.getBoundingClientRect", "getBoundingClientRect()")}} on the target. This is the largest the intersection rectangle may be. The remaining steps will remove any portions that don't intersect.
  2. -
  3. Starting at the target's immediate parent block and moving outward, each containing block's clipping (if any) is applied to the intersection rectangle. A block's clipping is determined based on the intersection of the two blocks and the clipping mode (if any) specified by the {{cssxref("overflow")}} property. Setting overflow to anything but visible causes clipping to occur.
  4. -
  5. If one of the containing elements is the root of a nested browsing context (such as the document contained in an {{HTMLElement("iframe")}}, the intersection rectangle is clipped to the containing context's viewport, and recursion upward through the containers continues with the container's containing block. So if the top level of an <iframe> is reached, the intersection rectangle is clipped to the frame's viewport, then the frame's parent element is the next block recursed through toward the intersection root.
  6. -
  7. When recursion upward reaches the intersection root, the resulting rectangle is mapped to the intersection root's coordinate space.
  8. -
  9. The resulting rectangle is then updated by intersecting it with the root intersection rectangle.
  10. -
  11. This rectangle is, finally, mapped to the coordinate space of the target's {{domxref("document")}}.
  12. -
- -

Intersection change callbacks

- -

When the amount of a target element which is visible within the root element crosses one of the visibility thresholds, the {{domxref("IntersectionObserver")}} object's callback is executed. The callback receives as input an array of all of IntersectionObserverEntry objects, one for each threshold which was crossed, and a reference to the IntersectionObserver object itself.

- -

Each entry in the list of thresholds is an {{domxref("IntersectionObserverEntry")}} object describing one threshold that was crossed; that is, each entry describes how much of a given element is intersecting with the root element, whether or not the element is considered to be intersecting or not, and the direction in which the transition occurred.

- -

The code snippet below shows a callback which keeps a counter of how many times elements transition from not intersecting the root to intersecting by at least 75%.

- -
intersectionCallback(entries) => {
-  entries.forEach(entry => {
-    if (entry.isIntersecting) {
-      let elem = entry.target;
-
-      if (entry.intersectionRatio >= 0.75) {
-        intersectionCounter++;
-      }
-    }
-  });
-}
-
- -

Інтерфейси

- -
-
{{domxref("IntersectionObserver")}}
-
Основний інтерфейс для API Intersection Observer. Надає методи для створення і керування observer, який може спостерігати будь-яку кількість цільових елементів для однієї і тієї ж конфігурації перетину. Кожен observer може асинхронно спостерігати зміни в перетині між одним чи кількома цільовими елементами і спільним елементом-батьком чи з їх верхнім рівнем Document's viewport. Батько чи область перегляду згадується як root.
-
{{domxref("IntersectionObserverEntry")}}
-
-

Описує перетин між цільовим елементом і його кореневим контейнером в певний момент переходу. Об'єкти цього типу можуть бути отримані тільки двома способами: в якості вхідних даних для вашого зворотнього виклику IntersectionObserver чи шляхом виклику {{domxref("IntersectionObserver.takeRecords()")}}.

-
-
- -

A simple example

- -

This simple example causes a target element to change its color and transparency as it becomes more or less visible. At Timing element visibility with the Intersection Observer API, you can find a more extensive example showing how to time how long a set of elements (such as ads) are visible to the user and to react to that information by recording statistics or by updating elements..

- -

HTML

- -

The HTML for this example is very short, with a primary element which is the box that we'll be targeting (with the creative ID "box") and some contents within the box.

- -
<div id="box">
-  <div class="vertical">
-    Welcome to <strong>The Box!</strong>
-  </div>
-</div>
- -

CSS

- -

The CSS isn't terribly important for the purposes of this example; it lays out the element and establishes that the {{cssxref("background-color")}} and {{cssxref("border")}} attributes can participate in CSS transitions, which we'll use to affect the changes to the element as it becomes more or less obscured.

- -
#box {
-  background-color: rgba(40, 40, 190, 255);
-  border: 4px solid rgb(20, 20, 120);
-  transition: background-color 1s, border 1s;
-  width: 350px;
-  height: 350px;
-  display: flex;
-  align-items: center;
-  justify-content: center;
-  padding: 20px;
-}
-
-.vertical {
-  color: white;
-  font: 32px "Arial";
-}
-
-.extra {
-  width: 350px;
-  height: 350px;
-  margin-top: 10px;
-  border: 4px solid rgb(20, 20, 120);
-  text-align: center;
-  padding: 20px;
-}
- -

JavaScript

- -

Finally, let's take a look at the JavaScript code that uses the Intersection Observer API to make things happen.

- -

Setting up

- -

First, we need to prepare some variables and install the observer.

- -
const numSteps = 20.0;
-
-let boxElement;
-let prevRatio = 0.0;
-let increasingColor = "rgba(40, 40, 190, ratio)";
-let decreasingColor = "rgba(190, 40, 40, ratio)";
-
-// Set things up
-window.addEventListener("load", (event) => {
-  boxElement = document.querySelector("#box");
-
-  createObserver();
-}, false);
- -

The constants and variables we set up here are:

- -
-
numSteps
-
A constant which indicates how many thresholds we want to have between a visibility ratio of 0.0 and 1.0.
-
prevRatio
-
This variable will be used to record what the visibility ratio was the last time a threshold was crossed; this will let us figure out whether the target element is becoming more or less visible.
-
increasingColor
-
A string defining a color we'll apply to the target element when the visibility ratio is increasing. The word "ratio" in this string will be replaced with the target's current visibility ratio, so that the element not only changes color but also becomes increasingly opaque as it becomes less obscured.
-
decreasingColor
-
Similarly, this is a string defining a color we'll apply when the visibility ratio is decreasing.
-
- -

We call {{domxref("EventTarget.addEventListener", "Window.addEventListener()")}} to start listening for the {{event("load")}} event; once the page has finished loading, we get a reference to the element with the ID "box" using {{domxref("Document.querySelector", "querySelector()")}}, then call the createObserver() method we'll create in a moment to handle building and installing the intersection observer.

- -

Creating the intersection observer

- -

The createObserver() method is called once page load is complete to handle actually creating the new {{domxref("IntersectionObserver")}} and starting the process of observing the target element.

- -
function createObserver() {
-  let observer;
-
-  let options = {
-    root: null,
-    rootMargin: "0px",
-    threshold: buildThresholdList()
-  };
-
-  observer = new IntersectionObserver(handleIntersect, options);
-  observer.observe(boxElement);
-}
- -

This begins by setting up an options object containing the settings for the observer. We want to watch for changes in visibility of the target element relative to the document's viewport, so root is null. We need no margin, so the margin offset, rootMargin, is specified as "0px". This causes the observer to watch for changes in the intersection between the target element's bounds and those of the viewport, without any added (or subtracted) space.

- -

The list of visibility ratio thresholds, threshold, is constructed by the function buildThresholdList(). The threshold list is built programmatically in this example since there are a number of them and the number is intended to be adjustable.

- -

Once options is ready, we create the new observer, calling the {{domxref("IntersectionObserver.IntersectionObserver", "IntersectionObserver()")}} constructor, specifying a function to be called when intersection crosses one of our thresholds, handleIntersect(), and our set of options. We then call {{domxref("IntersectionObserver.observe", "observe()")}} on the returned observer, passing into it the desired target element.

- -

We could opt to monitor multiple elements for visibility intersection changes with respect to the viewport by calling observer.observe() for each of those elements, if we wanted to do so.

- -

Building the array of threshold ratios

- -

The buildThresholdList() function, which builds the list of thresholds, looks like this:

- -
function buildThresholdList() {
-  let thresholds = [];
-  let numSteps = 20;
-
-  for (let i=1.0; i<=numSteps; i++) {
-    let ratio = i/numSteps;
-    thresholds.push(ratio);
-  }
-
-  thresholds.push(0);
-  return thresholds;
-}
- -

This builds the array of thresholds—each of which is a ratio between 0.0 and 1.0, by pushing the value i/numSteps onto the thresholds array for each integer i between 1 and numSteps. It also pushes 0 to include that value. The result, given the default value of numSteps (20), is the following list of thresholds:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#Ratio#Ratio
10.05110.55
20.1120.6
30.15130.65
40.2140.7
50.25150.75
60.3160.8
70.35170.85
80.4180.9
90.45190.95
100.5201.0
- -

We could, of course, hard-code the array of thresholds into our code, and often that's what you'll end up doing. But this example leaves room for adding configuration controls to adjust the granularity, for example.

- -

Handling intersection changes

- -

When the browser detects that the target element (in our case, the one with the ID "box") has been unveiled or obscured such that its visibility ratio crosses one of the thresholds in our list, it calls our handler function, handleIntersect():

- -
function handleIntersect(entries, observer) {
-  entries.forEach((entry) => {
-    if (entry.intersectionRatio > prevRatio) {
-      entry.target.style.backgroundColor = increasingColor.replace("ratio", entry.intersectionRatio);
-    } else {
-      entry.target.style.backgroundColor = decreasingColor.replace("ratio", entry.intersectionRatio);
-    }
-
-    prevRatio = entry.intersectionRatio;
-  });
-}
- -

For each {{domxref("IntersectionObserverEntry")}} in the list entries, we look to see if the entry's {{domxref("IntersectionObserverEntry.intersectionRatio", "intersectionRatio")}} is going up; if it is, we set the target's {{cssxref("background-color")}} to the string in increasingColor (remember, it's "rgba(40, 40, 190, ratio)"), replaces the word "ratio" with the entry's intersectionRatio. The result: not only does the color get changed, but the transparency of the target element changes, too; as the intersection ratio goes down, the background color's alpha value goes down with it, resulting in an element that's more transparent.

- -

Similarly, if the intersectionRatio is going down, we use the string decreasingColor and replace the word "ratio" in that with the intersectionRatio before setting the target element's background-color.

- -

Finally, in order to track whether the intersection ratio is going up or down, we remember the current ratio in the variable prevRatio.

- -

Result

- -

Below is the resulting content. Scroll this page up and down and notice how the appearance of the box changes as you do so.

- -

{{EmbedLiveSample('A_simple_example', 400, 400)}}

- -

There's an even more extensive example at Timing element visibility with the Intersection Observer API.

- -

Specifications

- - - - - - - - - - - - - - - - -
SpecificationStatusComment
{{SpecName('IntersectionObserver')}}{{Spec2('IntersectionObserver')}}
- -

Browser compatibility

- - - -

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

- -

See also

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