【问题标题】:How to listen for layout changes on a specific HTML element?如何监听特定 HTML 元素的布局变化?
【发布时间】:2012-11-02 00:07:11
【问题描述】:

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

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

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

【问题讨论】:

  • 您是想自己做,还是有可用的库?如果您有 jQuery,可能需要查看 jQuery watch plugin
  • 更改内容时可以触发事件吗?
  • 谢谢,Ktash 和艾伦。愿意发布任何示例吗?我更愿意接受带有工作代码的答案。

标签: javascript html css layout reflow


【解决方案1】:

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

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

}

【讨论】:

  • 谢谢,狄奥德斯。环顾四周,我认为是这种情况,但我正在寻找这样做的技术。想发布一个例子吗?
  • 你想要一个 jQuery 示例吗?
【解决方案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
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多