7

有哪些技术可以在现代浏览器中监听布局变化?window.resize不起作用,因为它仅在调整整个窗口大小时触发,而不是在内容更改导致重排时触发。

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

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

2 回答 2

8

没有本地事件可以为此挂钩。您需要设置一个计时器并在您自己的代码中轮询此元素的尺寸。

这是基本版本。它每 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)
     } 

}
于 2012-11-13T15:10:45.673 回答
2

从一个类似的问题How to know when an DOM element move or is resized中,有一个来自 Ben Alman 的 jQuery 插件可以做到这一点。该插件使用 Diodeus 的答案中概述的相同轮询方法。

插件页面的示例:

// Well, try this on for size!
$("#unicorns").resize(function(e){
  // do something when #unicorns element resizes
});
于 2012-11-21T03:18:26.970 回答