How to detect DIV#39;s dimension changed?(如何检测 DIV 的尺寸变化?)
问题描述
我有以下示例 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="aHR0cDovL2NvZGUuanF1ZXJ5LmNvbS9qcXVlcnktMS42LjEubWluLmpz"></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.
披露:我与这个库直接相关.
这篇关于如何检测 DIV 的尺寸变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检测 DIV 的尺寸变化?


- 为什么悬停在委托事件处理程序中不起作用? 2022-01-01
- 使用 iframe URL 的 jQuery UI 对话框 2022-01-01
- 为什么我的页面无法在 Github 上加载? 2022-01-01
- 在不使用循环的情况下查找数字数组中的一项 2022-01-01
- 是否可以将标志传递给 Gulp 以使其以不同的方式 2022-01-01
- 如何向 ipc 渲染器发送添加回调 2022-01-01
- 从原点悬停时触发 translateY() 2022-01-01
- 我不能使用 json 使用 react 向我的 web api 发出 Post 请求 2022-01-01
- 如何调试 CSS/Javascript 悬停问题 2022-01-01
- 如何显示带有换行符的文本标签? 2022-01-01