resize_看看Resize Observer JavaScript API

news/2024/7/3 19:43:37

resize

Resize Observer is a new JavaScript API that’s very similar to other observer APIs like the Intersection Observer API. It allows for elements to be notified when their size changes.

Resize Observer是一个新JavaScript API,与诸如Intersection Observer API之类的其他观察者API非常相似。 它允许在元素大小更改时通知元素。

The most frequent reason for an element’s size to change is when the viewport is resized or the device’s direction changes between portrait and landscape. Up until this point, we’ve had to rely on the global window.resize event to listen for resize events and check if certain elements have changed size. This can easily lead to performance problems due to the large amount of triggered event. In other words, using window.resize is often wasteful because it informs us of every viewport size change, not just when an element’s size actually changes.

更改元素大小的最常见原因是调整视口大小或设备的方向在纵向和横向之间变化。 到目前为止,我们必须依靠全局window.resize事件来监听resize事件并检查某些元素是否已更改大小。 由于大量触发事件,这很容易导致性能问题。 换句话说,使用window.resize通常很浪费,因为它会通知我们每个视口大小的变化,而不仅仅是告知元素尺寸实际发生的变化。

There’s also another use case for the Resize Observer API that the window’s resize event can’t help us with: when elements are added or removed from the DOM dynamically, influencing the size of the parent element. This is more and more frequent with modern single-page apps.

Resize Observer API的另一个用例是窗口的resize事件无法帮助我们:动态添加或从DOM中删除元素时,会影响父元素的大小。 对于现代的单页应用程序,这种情况越来越常见。

基本用法 (Basic Usage)

Using Resize Observer is as simple as instantiating a new ResizeObserver object and passing-in a callback function that receives the entries that are observed:

使用Resize Observer就像实例化一个新的ResizeObserver对象并传入一个回调函数一样简单,该回调函数接收观察到的条目:

const myObserver = new ResizeObserver(entries => {
  // iterate over the entries, do something.
});

Then, we can call observe on our instance and pass-in an element to observe:

然后,我们可以在实例上调用observe ,并传入一个元素进行观察:

const someEl = document.querySelector('.some-element');
const someOtherEl = document.querySelector('.some-other-element');

myObserver.observe(someEl);
myObserver.observe(someOtherEl);

With each entry, we get an object with a contentRect and a target property. The target is the DOM element itself, and contentRect is an object with the following properties: width, height, x, y, top, right, bottom and left.

对于每个条目,我们都会获得一个具有contentRect和target属性的对象 。 目标是DOM元素本身, contentRect是具有以下属性的对象: width , height , x , y , top , right , bottom和left 。

Unlike with an element’s getBoundingClientRect, contentRect’s values for width and height don’t include padding values. contentRect.top is the element’s top padding and contentRect.left is the element’s left padding.

与元素的getBoundingClientRect不同,contentRect的width和height的值不包含填充值。 contentRect.top是元素的顶部填充, contentRect.left是元素的左侧填充。



If, for example, we want log an observed element’s width and height when the element’s size changes, we could do something like this:

例如,如果我们想在元素大小改变时记录观察到的元素的宽度和高度,则可以执行以下操作:

const myObserver = new ResizeObserver(entries => {
  entries.forEach(entry => {
    console.log('width', entry.contentRect.width);
    console.log('height', entry.contentRect.height);
  });
});

const someEl = document.querySelector('.some-element');
myObserver.observe(someEl);

简单演示 (Simple Demo)

Below is a simple demonstration to see the Resize Observer API in action. Try it out by resizing your browser window and notice how the gradient angle and text content only change when the element’s size is actually affected:

以下是一个简单的演示,以了解实际中的Resize Observer API。 通过调整浏览器窗口的大小来尝试一下,请注意仅当元素的大小实际受到影响时,渐变角度和文本内容才会发生变化:



Let’s break down this simple demo. First, we start with some simple markup:

让我们分解一下这个简单的演示。 首先,我们从一些简单的标记开始:

<div class="box">
  <h3 class="info"></h3>
</div>
<div class="box small">
  <h3 class="info"></h3>
</div>

And a touch of styles:

还有一点风格:

.box {
  text-align: center;
  height: 20vh;
  border-radius: 8px;
  box-shadow: 0 0 4px var(--subtle);

  display: flex;
  justify-content: center;
  align-items: center;
}

.box h3 {
  color: #fff;
  margin: 0;
  font-size: 5vmin;
  text-shadow: 0 0 10px rgba(0,0,0,0.4);
}

.box.small {
  max-width: 550px;
  margin: 1rem auto;
}

Notice how we don’t need to apply our gradient background to the .box element. The resize observer will be called once when the page first loads and our gradient will be applied then.

注意,我们不需要将渐变背景应用于.box元素。 第一次加载页面时,将调用一次大小调整观察器,然后应用渐变。

Now, the magic happens when we add the following JavaScript code:

现在,当我们添加以下JavaScript代码时,魔术就发生了:

const boxes = document.querySelectorAll('.box');

const myObserver = new ResizeObserver(entries => {
  for (let entry of entries) {
    const infoEl = entry.target.querySelector('.info');
    const width = Math.floor(entry.contentRect.width);
    const height = Math.floor(entry.contentRect.height);

    const angle = Math.floor(width / 360 * 100);
    const gradient = `linear-gradient(${ angle }deg, rgba(0,143,104,1) 50%, rgba(250,224,66,1) 50%)`;

    entry.target.style.background = gradient;

    infoEl.innerText = `I'm ${ width }px and ${ height }px tall`;
  }
});

boxes.forEach(box => {
  myObserver.observe(box);
});

Here we’re iterating over the entries in the observer’s callback using a for…of loop, but calling forEach on the entries would work just the same.

在这里,我们使用for…of循环遍历观察者回调中的条目 ,但是在条目上调用forEach相同。

Notice how we also have to iterate over the elements that we can to observe and call observe on each element.

注意,我们还必须遍历可以观察的元素,并在每个元素上调用observe

浏览器支持 (Browser Support)

Browser support right now is pretty bad, with only Chrome 64+ supporting Resize Observer out of the box. Thankfully, there’s a polyfill we can use in the mean time. The polyfill is based on the MutationObserver API.

目前,浏览器支持非常糟糕,只有Chrome 64+支持开箱即用的Resize Observer。 值得庆幸的是,在此期间我们可以使用一个polyfill 。 该polyfill基于MutationObserver API 。

You can visit Can I Use resizeobserver? to track support for this feature across the major browsers.

您可以访问我可以使用resizeobserver吗? 跟踪主要浏览器对此功能的支持。

翻译自: https://www.digitalocean.com/community/tutorials/js-resize-observer

resize


http://www.niftyadmin.cn/n/3648310.html

相关文章

新闻聚合引擎能把新闻组织到什么程度? 兼谈百度google新闻

zhengyun_ustc 2007-3-31书接上回《自然语言处理能够把全网内容组织到什么程度&#xff1f;》。百度新闻和google新闻都是不错的新闻聚合&#xff0c;内容组织得不错。那么我们的机会又在哪里呢&#xff1f;我们怎么才能提供一个新闻事件脉络呢&#xff1f;后面我会讲到百度和g…

javascript控制台_看一下JavaScript控制台API

javascript控制台The JavaScript console is an invaluable tool to help develop and debug our apps. With the console object and its logging methods, long are the days of of calling alert() to debug and get a variable’s value. On top of that, thanks to a work…

技术英雄会【一】:问周鸿祎一个问题

zhengyun_ustc 20070406下午创业英雄论坛&#xff0c;周鸿祎是被问问题最多的&#xff0c;也是最能讲的。周董也延续了以往的直言不讳。其中有一些说法和他以前的公开文字差不多&#xff0c;比如“创业心态&#xff1a;考虑失败比考虑成功多”&#xff0c;比如“成功者的创业初…

react前端ui的使用_使用React Morph变形UI过渡

react前端ui的使用Love them or hate them, animations in modern web design are probably here to stay. Unlike the glory days of jQuery, React out of the box does not provide any mechanism to perform such animations. Sure you could do a small bit of CSS wizard…

技术英雄会【新闻】CSDN最有价值博客TOP10颁奖【图】【我在左边数第四个】

2007年04月06日 10:04 新浪科技夹带些私货&#xff0c;呵呵&#xff1a;社区英雄会【一】&#xff1a;问周鸿祎一个问题社区英雄会【二】&#xff1a;问CSDN一个信息过滤器的问题技术英雄会【三】&#xff1a;社区英雄们的与会感言大赏技术英雄会【四】&#xff1a;也谈如何发…

Python 简介

Python - 简介 PythonPython&#xff08;[KK] 英语发音&#xff1a; /paɪθɑn/, [DJ] 英语发音&#xff1a; /ˈpaiθən/&#xff09;&#xff0c;是一种面向对象、直译式的计算机程序设计语言&#xff0c;也是一种功能强大的通用型语言&#xff0c;已经具有近二十年的发展历…

如何使用Google Chrome DevTools和Visual Studio Code调试JavaScript

介绍 (Introduction) Learning to debug is an essential skill for developers, as it allows them to efficiently fix errors during development. Knowing how to use debugging tools may not always be obvious when working with JavaScript outside of an integrated d…

技术英雄会【二】:问CSDN一个信息过滤器的问题

zhengyun_ustc 20070406刘韧的《4月6日CSDN软件英雄会》中&#xff0c;这句话无意中透露出了CSDN的一个野心&#xff1a;“CSDN这个过滤器&#xff0c;将108人筛选出来&#xff0c;给了这108人抛头露面的机会&#xff0c;这108人同时也成了投资人、创业者、合作者的机会。”4月…