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

当前回答

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

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

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

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

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

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

其他回答

从长远来看,您将能够使用ResizeObserver。

new ResizeObserver(callback).observe(element);

不幸的是,目前许多浏览器默认不支持它。

同时,您可以像下面这样使用函数。因为,大部分元素大小的变化将来自窗口大小的调整或DOM中的某些更改。你可以通过窗口的resize事件来监听窗口的大小调整,也可以使用MutationObserver监听DOM的变化。

下面是一个函数的例子,当提供的元素的大小因为这两个事件中的任何一个而改变时,它会回调你:

var onResize = function(element, callback) {
  if (!onResize.watchedElementData) {
    // First time we are called, create a list of watched elements
    // and hook up the event listeners.
    onResize.watchedElementData = [];

    var checkForChanges = function() {
      onResize.watchedElementData.forEach(function(data) {
        if (data.element.offsetWidth !== data.offsetWidth ||
            data.element.offsetHeight !== data.offsetHeight) {
          data.offsetWidth = data.element.offsetWidth;
          data.offsetHeight = data.element.offsetHeight;
          data.callback();
        }
      });
    };

    // Listen to the window's size changes
    window.addEventListener('resize', checkForChanges);

    // Listen to changes on the elements in the page that affect layout 
    var observer = new MutationObserver(checkForChanges);
    observer.observe(document.body, { 
      attributes: true,
      childList: true,
      characterData: true,
      subtree: true 
    });
  }

  // Save the element we are watching
  onResize.watchedElementData.push({
    element: element,
    offsetWidth: element.offsetWidth,
    offsetHeight: element.offsetHeight,
    callback: callback
  });
};

我认为这是不可能的,但后来我想了一下,你可以手动调整一个div通过style="resize: both;"为了做到这一点,你必须点击它,所以添加了一个onclick函数来检查元素的高度和宽度,它工作。只有5行纯javascript(当然可以更短) http://codepen.io/anon/pen/eNyyVN

<div id="box" style="
                height:200px; 
                width:640px;
                background-color:#FF0066;
                resize: both;
                overflow: auto;" 
                onclick="myFunction()">
    <p id="sizeTXT" style="
                font-size: 50px;">
       WxH
    </p>
    </div>

<p>This my example demonstrates how to run a resize check on click for resizable div.</p>

<p>Try to resize the box.</p>


<script>
function myFunction() {
var boxheight = document.getElementById('box').offsetHeight;
var boxhwidth = document.getElementById('box').offsetWidth;
var txt = boxhwidth +"x"+boxheight;
document.getElementById("sizeTXT").innerHTML = txt;
}
</script>

唯一的窗户。onResize存在于规范中,但你总是可以利用IFrame在DIV中生成新的Window对象。

请核对这个答案。有一个新的jquery插件,它是可移植的,易于使用。您总是可以检查源代码,看看它是如何完成的。

<!-- (1) include plugin script in a page -->
<script src="/src/jquery-element-onresize.js"></script>

// (2) use the detectResizing plugin to monitor changes to the element's size:
$monitoredElement.detectResizing({ onResize: monitoredElement_onResize });

// (3) write a function to react on changes:
function monitoredElement_onResize() {    
    // logic here...
}

我的jQuery插件在所有元素上启用了“调整大小”事件,而不仅仅是窗口。

https://github.com/dustinpoissant/ResizeTriggering

$("#myElement") .resizeTriggering().on("resize", function(e){
  // Code to handle 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>