简体   繁体   English

我如何限制 ResizeObserver?

[英]How can I throttle a ResizeObserver?

I currently use a ResizeObserver to watch the size of an element but I was thinking of using a throttle (lodash's throttle) to increase the performance of it.我目前使用 ResizeObserver 来观察元素的大小,但我正在考虑使用节流阀(lodash 的节流阀)来提高它的性能。

const myResize = new ResizeObserver((entries) => {
    const el = document.querySelector('#foo');
    // get boundingRect and adjust height
});

let imageToWatch = document.querySelector('.image');
myResize.observe(imageToWatch);

is there a way I can throttle this?有什么办法可以throttle吗? Would the throttle just be on the logic inside myResize ?节气门是否只是在myResize内部的逻辑上? I assume I can't throttle the observe portion of this though.我想我不能限制这个的observe部分。

The behaviour of ResizeObserver could only be modified if you would recreate that constructor. ResizeObserver的行为只有在您重新创建该构造函数时才能修改。 It will indeed be simpler to just throttle the callback function that you pass to that constructor.限制传递给该构造函数的回调 function 确实会更简单。

To demo this, here is a textarea element, which by default can be resized interactively.为了演示这一点,这里有一个textarea元素,默认情况下可以交互调整大小。 The handler will change the background color of the textarea, but only if 1 second passed after the last event.处理程序将更改文本区域的背景颜色,但前提是在最后一个事件后经过 1 秒。 For this purpose the handler is wrapped in a call to throttle(f, delay) :为此,处理程序被包装在对throttle(f, delay)的调用中:

 function throttle(f, delay) { let timer = 0; return function(...args) { clearTimeout(timer); timer = setTimeout(() => f.apply(this, args), delay); } } const myResize = new ResizeObserver(throttle((entries) => { entries[0].target.style.backgroundColor = "#" + (Math.random() * 4096 | 0).toString(16); }, 1000)); const elemToWatch = document.querySelector('textarea'); myResize.observe(elemToWatch);
 <textarea></textarea>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM