如何监听特定HTML元素的布局更改?

Chr*_*alo 4 html javascript css layout reflow

在现代浏览器中监听布局更改的一些技巧是什么?window.resize将无法正常工作,因为它仅在整个窗口调整大小时触发,而不是在内容更改导致重排时触发.

具体来说,我想知道什么时候:

  • 元素的可用宽度会发生变化.
  • 元素的流入子元素消耗的总高度会发生变化.

Dio*_*ane 6

没有本地事件可以为此加入.您需要设置一个计时器并在您自己的代码中轮询此元素的维度.

这是基本版本.它每100毫秒轮询一次.我不确定你要怎么检查孩子的身高.这假设他们只是让他们的包装更高.

var origHeight = 0;
var origWidth = 0;
var timer1;

function testSize() {
     var $target = $('#target')     
     if(origHeight==0) {
         origWidth = $target.outerWidth();
         origHeight = $target.outerHeight();

     }
     else {
         if(origWidth != $target.outerWidth() || origHeight = $target.outerHeight()) {
             alert("change");  
         }
         origWidth = $target.outerWidth();
         origHeight = $target.outerHeight();
         timer1= window.setTimeout(function(){ testSize() }),100)
     } 

}
Run Code Online (Sandbox Code Playgroud)


mam*_*don 5

新的浏览器现在具有ResizeObserver,当元素的内容框或边框框的尺寸发生更改时会触发该函数。

\n
const observer = new ResizeObserver(entries => {\n  const entry = entries[0];\n  console.log(\'contentRect\', entry.contentRect);\n  // do other work here\xe2\x80\xa6\n});\n\nobserver.observe(element);\n
Run Code Online (Sandbox Code Playgroud)\n