且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检测DIV的维度变化?

更新时间:2023-02-26 15:06:49

有一种非常有效的方法来确定元素大小已更改。

http: //marcj.github.io/css-element-queries/



这个库有一个类 ResizeSensor code> ,可用于调整大小检测。

它使用基于事件的方法,因此速度很快,并且不会浪费CPU时间。



示例:

  new ResizeSensor(jQuery('#divId'),function(){
console.log('content dimension changed');
} );

请勿使用 jQuery onresize插件,因为它使用 setTimeout()循环来检查更改。
这个速度慢,不准确



披露:我直接与这个库相关联。


I've the following sample html, there is a DIV which has 100% width. It contains some elements. While performing windows re-sizing, the inner elements may be re-positioned, and the dimension of the div may change. I'm asking if it is possible to hook the div's dimension change event? and How to do that? I currently bind the callback function to the jQuery resize event on the target DIV, however, no console log is outputted, see below:

<html>
<head>
    <script type="text/javascript" language="javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
    <script type="text/javascript" language="javascript">
            $('#test_div').bind('resize', function(){
                console.log('resized');
            });
    </script>
</head>
<body>
    <div id="test_div" style="width: 100%; min-height: 30px; border: 1px dashed pink;">
        <input type="button" value="button 1" />
        <input type="button" value="button 2" />
        <input type="button" value="button 3" />
    </div>
</body>
</html>

There is a very efficient method to determine if a element's size has been changed.

http://marcj.github.io/css-element-queries/

This library has a class ResizeSensor which can be used for resize detection.
It uses an event-based approach, so it's damn fast and doesn't waste CPU time.

Example:

new ResizeSensor(jQuery('#divId'), function(){ 
    console.log('content dimension changed');
});

Please do not use the jQuery onresize plugin as it uses setTimeout() loop to check for changes.
THIS IS INCREDIBLY SLOW AND NOT ACCURATE.

Disclosure: I am directly associated with this library.