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

时间:2012-11-13 14:48:09

标签: javascript html css layout reflow

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

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

  • 元素的可用宽度发生变化。
  • 元素的in-flow子元素消耗的总高度会发生变化。

2 个答案:

答案 0 :(得分: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)
     } 

}

答案 1 :(得分:2)

从类似的问题How to know when an DOM element moves or is resized,有一个jQuery plugin from Ben Alman就是这样做的。此插件使用Diodeus答案中概述的相同轮询方法。

插件页面中的示例:

// Well, try this on for size!
$("#unicorns").resize(function(e){
  // do something when #unicorns element resizes
});
相关问题