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

<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>

当前回答

看看这个http://benalman.com/code/projects/jquery-resize/examples/resize/

它有很多例子。尝试调整窗口大小,看看容器元素中的元素是如何调整的。

用js的例子来解释如何让它工作。 看看这小提琴http://jsfiddle.net/sgsqJ/4/

在这个resize()事件中,它被绑定到具有类“test”的元素以及窗口对象 在窗口对象$('.test')的resize回调中调用.resize()。

e.g.

$('#test_div').bind('resize', function(){
            console.log('resized');
});

$(window).resize(function(){
   $('#test_div').resize();
});

其他回答

纯香草的实现。

var move = function(e) { if ((e.w && e.w !== e.offsetWidth) || (e.h && e.h !== e.offsetHeight)) { new Function(e.getAttribute('onresize')).call(e); } e.w = e.offsetWidth; e.h = e.offsetHeight; } var resize = function(e) { e.innerText = 'New dimensions: ' + e.w + ',' + e.h; } .resizable { resize: both; overflow: auto; width: 200px; border: 1px solid black; padding: 20px; } <div class='resizable' onresize="resize(this)" onmousemove="move(this)"> Pure vanilla implementation </div>

您必须将resize事件绑定到窗口对象上,而不是绑定到通用html元素上。

然后你可以使用这个:

$(window).resize(function() {
    ...
});

在回调函数中,你可以检查div调用的新宽度

$('.a-selector').width();

因此,您的问题的答案是否定的,您不能将resize事件绑定到div。

有一种非常有效的方法来确定元素的大小是否已经改变。

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

这个库有一个resizessensor类,可以用于调整大小检测。它使用基于事件的方法,所以它非常快,而且不会浪费CPU时间。

例子:

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

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

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

令人惊讶的是,尽管这个问题已经存在很久了,但在大多数浏览器中仍然存在这个问题。

正如其他人所说,Chrome 64+现在自带Resize observed,然而,该规范仍在微调中,Chrome目前(截至2019-01-29)落后于最新版本的规范。

我已经在野外看到了一些很好的ResizeObserver腻子,但是,一些没有严格遵循规范,另一些有一些计算问题。

我迫切需要这种行为来创建一些可以在任何应用程序中使用的响应式web组件。为了使他们工作得很好,他们需要随时知道他们的尺寸,所以ResizeObservers听起来很理想,我决定创建一个尽可能严格遵循规范的填充。

回购协议: https://github.com/juggle/resize-observer

演示: https://codesandbox.io/s/myqzvpmmy9

jQuery(document).ready( function($) {

function resizeMapDIVs() {

// check the parent value...

var size = $('#map').parent().width();



if( $size < 640 ) {

//  ...and decrease...

} else {

//  ..or increase  as necessary

}

}

resizeMapDIVs();

$(window).resize(resizeMapDIVs);

});