如何检测DIV的维度改变? [英] How to detect DIV's dimension changed?

查看:24
本文介绍了如何检测DIV的维度改变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

<头><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('调整大小');});<身体><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"/>

解决方案

有一种非常有效的方法可以确定元素的大小是否已更改.

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

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

示例:

new ResizeSensor(jQuery('#divId'), function(){console.log('内容维度改变');});

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

披露:我与这个图书馆直接相关.

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() 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.

Disclosure: I am directly associated with this library.

这篇关于如何检测DIV的维度改变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆