How to detect DIV's dimension changed?

后端 未结 25 2690
抹茶落季
抹茶落季 2020-11-22 06:14

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,

25条回答
  •  滥情空心
    2020-11-22 06:33

    Long term, you will be able to use the ResizeObserver.

    new ResizeObserver(callback).observe(element);
    

    Unfortunately it is not currently supported by default in many browsers.

    In the mean time, you can use function like the following. Since, the majority of element size changes will come from the window resizing or from changing something in the DOM. You can listen to window resizing with the window's resize event and you can listen to DOM changes using MutationObserver.

    Here's an example of a function that will call you back when the size of the provided element changes as a result of either of those events:

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

提交回复
热议问题