如何检测 DIV 的尺寸变化?

2022-01-30 00:00:00 jquery javascript html

我有以下示例 html,其中有一个 100% 宽度的 DIV.它包含一些元素.在执行窗口大小调整时,内部元素可能会重新定位,并且 div 的尺寸可能会发生变化.我在问是否可以挂钩 div 的维度更改事件?以及如何做到这一点?我目前将回调函数绑定到目标DIV上的jQuery resize事件,但是没有输出控制台日志,见下文:

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/

这个库有一个类 ResizeSensor 可用于调整大小检测.
它使用基于事件的方法,因此速度非常快,而且不会浪费 CPU 时间.

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.

例子:

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

请不要使用 jQuery onresize 插件,因为它使用 setTimeout() 结合读取 DOM clientHeight/clientWidth 循环中的属性以检查更改.
这是非常缓慢且不准确的,因为它会导致布局抖动.

Please do not use the jQuery onresize plugin as it uses setTimeout() in combination with reading the DOM clientHeight/clientWidth properties in a loop to check for changes.
This is incredible slow and inaccurate since it causes layout thrashing.

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

相关文章