我有下面的样本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>

当前回答

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

});

其他回答

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

然后你可以使用这个:

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

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

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

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

使用Clay.js (https://github.com/zzarcon/clay),检测元素大小的变化非常简单:

var el = new Clay('.element');

el.on('resize', function(size) {
    console.log(size.height, size.width);
});

只有窗口对象生成“调整大小”事件。我所知道的唯一方法是运行一个间隔计时器,定期检查大小。

您可以使用iframe或对象使用contentWindow或contentDocument调整大小。没有setInterval或setTimeout

的步骤:

将元素位置设置为相对位置 在里面添加一个透明的绝对隐藏IFRAME 听IFRAME。contentWindow - onresize事件

HTML的一个例子:

<div style="height:50px;background-color:red;position:relative;border:1px solid red">
<iframe style=width:100%;height:100%;position:absolute;border:none;background-color:transparent allowtransparency=true>
</iframe>
This is my div
</div>

Javascript:

$('div').width(100).height(100);
$('div').animate({width:200},2000);

$('object').attr({
    type : 'text/html'
})
$('object').on('resize,onresize,load,onload',function(){
    console.log('ooooooooonload')
})

$($('iframe')[0].contentWindow).on('resize',function(){
    console.log('div changed')
})

运行示例

JsFiddle: https://jsfiddle.net/qq8p470d/


看到更多:

粘土-它是基于元素-大小调整事件 element-resize-event

一个更新的标准是Resize Observer api,有很好的浏览器支持。

函数输出大小() { 宽度.值 = 文本框偏移宽度 高度.值 = 文本框偏移高度 } 输出大小() new ResizeObserver (outputsize).observe(textbox) 宽度:<输出 id=“宽度”>0</output><br> 高度:<输出 id=“高度”>0</output><br> <textarea id=“textbox”>调整我</textarea><br>的大小

调整观察者

文档:https://developer.mozilla.org/en-US/docs/Web/API/Resize_Observer_API

规范:https://wicg.github.io/ResizeObserver

当前支持:http://caniuse.com/#feat=resizeobserver

填充物:https://github.com/pelotoncycle/resize-observer https://github.com/que-etc/resize-observer-polyfill https://github.com/juggle/resize-observer