Javascript ResizeObserver 被意外触发
Javascript ResizeObserver is triggered unexpected
为什么 ResizeObserver
class 总是在第一个 observe()
执行处理程序?
尝试在 Chrome' 开发工具上执行以下代码:
(new ResizeObserver(() => console.log('resize detected'))).observe([=11=])
您将在应用后立即看到打印的日志,即使您没有进行任何尺寸更改也是如此。
我需要仅在调整大小时执行处理程序的调整大小观察器。
有什么hack/options可以调整吗?
let disableObserver = false;
const obs = new ResizeObserver(() => {
if (!disableObserver) {
console.log('resize detected');
}
});
// the hack below doesn't work:
disableObserver = true;
obs.observe(someElement);
disableObserver = false;
在不同的浏览器中测试,报告的行为是一致的 - 在调用 observer()
时调用观察者回调。
我检查了 specification,它说:
- Observation will fire when watched Element is inserted/removed from DOM.
- Observation will fire when watched Element display gets set to none.
- Observations do not fire for non-replaced inline Elements.
- Observations will not be triggered by CSS transforms.
- Observation will fire when observation starts if Element is being rendered, and Element’s size is not 0,0.
我猜初始调用是因为正在渲染元素。
可以将每个元素添加到 Set 以跳过初始调用。像这样:
let entriesSeen = new Set(); // set of entries to skip initial resize call
const obs = new ResizeObserver((entries) => {
for (let entry of entries) {
if (!entriesSeen.has(entry.target)) {
// do nothing during initial call
// just mark element as seen
entriesSeen.add(entry.target);
} else {
console.log('resize detected');
console.log(entry.target);
}
}
});
obs.observe(someElement);
为什么 ResizeObserver
class 总是在第一个 observe()
执行处理程序?
尝试在 Chrome' 开发工具上执行以下代码:
(new ResizeObserver(() => console.log('resize detected'))).observe([=11=])
您将在应用后立即看到打印的日志,即使您没有进行任何尺寸更改也是如此。
我需要仅在调整大小时执行处理程序的调整大小观察器。
有什么hack/options可以调整吗?
let disableObserver = false;
const obs = new ResizeObserver(() => {
if (!disableObserver) {
console.log('resize detected');
}
});
// the hack below doesn't work:
disableObserver = true;
obs.observe(someElement);
disableObserver = false;
在不同的浏览器中测试,报告的行为是一致的 - 在调用 observer()
时调用观察者回调。
我检查了 specification,它说:
- Observation will fire when watched Element is inserted/removed from DOM.
- Observation will fire when watched Element display gets set to none.
- Observations do not fire for non-replaced inline Elements.
- Observations will not be triggered by CSS transforms.
- Observation will fire when observation starts if Element is being rendered, and Element’s size is not 0,0.
我猜初始调用是因为正在渲染元素。
可以将每个元素添加到 Set 以跳过初始调用。像这样:
let entriesSeen = new Set(); // set of entries to skip initial resize call
const obs = new ResizeObserver((entries) => {
for (let entry of entries) {
if (!entriesSeen.has(entry.target)) {
// do nothing during initial call
// just mark element as seen
entriesSeen.add(entry.target);
} else {
console.log('resize detected');
console.log(entry.target);
}
}
});
obs.observe(someElement);