gpt4 book ai didi

javascript - 如何使用 ResizeObserver 观察多个元素?

转载 作者:行者123 更新时间:2023-11-30 10:59:25 28 4
gpt4 key购买 nike

如何像所有文本区域一样使用 ResizeObserver 观察多个元素?使用 document.querySelectorAll() 会导致错误。

var ro = new ResizeObserver( entries => {
for (let entry of entries) {
// do something
}
});

// Works
ro.observe(document.querySelector('textarea'));

// Doesn't work
ro.observe(document.querySelectorAll("textarea"));


Error: VM112:8 Uncaught TypeError: Failed to execute 'observe' on 'ResizeObserver': parameter 1 is not of type 'Element'.
at <anonymous>:8:4

最佳答案

querySelectorAll返回 NodeList , 你可以使用 .forEach遍历每个并将其传递给观察者:

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

const myObserver = new ResizeObserver(entries => {
for (let entry of entries) {
const width = Math.floor(entry.contentRect.width);
const height = Math.floor(entry.contentRect.height);
entry.target.value = `I'm ${ width }px and ${ height }px tall`;
}
});

boxes.forEach(box => {
myObserver.observe(box);
});
.box {
text-align: center;
border: 1px solid black;
height: 100px;
border-radius: 8px;
display: flex;
}
<textarea class="box">
</textarea>
<textarea class="box">
</textarea>

编辑:您也可以一次观察单个元素,但它们需要单独初始化:

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

boxes.forEach(box => {
new ResizeObserver(entries => {
const width = Math.floor(entries[0].contentRect.width);
const height = Math.floor(entries[0].contentRect.height);
entries[0].target.value = `I'm ${ width }px and ${ height }px tall`;
}).observe(box);
});
.box {
text-align: center;
border: 1px solid black;
height: 100px;
border-radius: 8px;
display: flex;
}
<textarea class="box">
</textarea>
<textarea class="box">
</textarea>

关于javascript - 如何使用 ResizeObserver 观察多个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58519452/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com