未在 div 上触发调整大小事件

新手上路,请多包涵

看看这个例子: https ://jsfiddle.net/vxun2Lgg/2/

我在 container div 上附加了一个“调整大小”事件监听器。打开开发工具并修改 container 的宽度后,不会调用调整大小回调。我错过了什么?

PS:我对窗口调整大小事件不感兴趣,只对 container div 感兴趣。

 var container = document.getElementsByClassName("container")[0];
container.addEventListener("resize", function() {
  console.log("resizing")
});
 <div class="container"></div>

原文由 sanjihan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 276
2 个回答

resize 仅对 window 有效。 如果支持,您可以使用 ResizeObserver

 new ResizeObserver(() => console.log("resizing")).observe(container);

否则,您可能必须使用 setInterval 进行轮询并检查大小。

原文由 H.B. 发布,翻译遵循 CC BY-SA 3.0 许可协议

这个答案通过在纯 JavaScript 中提供一个 可运行的代码 来扩展已 接受 的答案,您可以在片段运行器(底部的按钮)上尝试该代码。我直接在代码上保留了解释。

信不信由你,您只需要一个 3 行函数( onresize 函数)来模拟调整大小事件。

好好享受!

 // This function works like an Event Listener for
// resizing a dom element.
//
// The ResizeObserver calls the callback function
//   whenever the size of the dom_element changes
//   (because it's "observing" the dom_elem)
//
// Do this:
//
//    understand_it_first
//       .then(copy_it)
//       .then(use_it);
//
// THIS IS THE 3-LINE FUNCION YOU WANT TO USE :)
//
const onresize = (dom_elem, callback) => {
  const resizeObserver = new ResizeObserver(() => callback() );
  resizeObserver.observe(dom_elem);
};

// USING IT
//

// Using constants to make it easier to read the code
//
const bb = document.getElementById('bad_boss');
const be = document.getElementById('bad_employee');

// Finally, register the observer for the dom_elem
//
onresize(bb, function () {
  be.style.width  = bb.offsetWidth + 'px';
  be.style.height = bb.offsetHeight + 'px';
});
 #bad_boss, #bad_employee{
  font-size        : 32px;
  height           : 200px;
  width            : 200px;
}

/* Colors that Talk*/

#bad_boss {
  background-color : #0badb055;
}
#bad_employee {
  background-color : #0b00c0de;
  color            : #0badc0de;
}
 <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>ResizeObserver - onresize Demo</title>
    </head>
    <body>
        <!-- Experiment to resize this <textarea> -->
        <textarea id="bad_boss">Always do whatever I say!</textarea>
        <div id="bad_employee">Always, Boss!</div>
    </body>
</html>

原文由 Almir Campos 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题