How to detect DIV's dimension changed?

后端 未结 25 2355
抹茶落季
抹茶落季 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:30

    Here is a simplified version of the solution by @nkron, applicable to a single element (instead of an array of elements in @nkron's answer, complexity I did not need).

    function onResizeElem(element, callback) {    
      // Save the element we are watching
      onResizeElem.watchedElementData = {
        element: element,
        offsetWidth: element.offsetWidth,
        offsetHeight: element.offsetHeight,
        callback: callback
      };
    
      onResizeElem.checkForChanges = function() {
        const data = onResizeElem.watchedElementData;
        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 resize event
      window.addEventListener('resize', onResizeElem.checkForChanges);
    
      // Listen to the element being checked for width and height changes
      onResizeElem.observer = new MutationObserver(onResizeElem.checkForChanges);
      onResizeElem.observer.observe(document.body, {
        attributes: true,
        childList: true,
        characterData: true,
        subtree: true
      });
    }
    

    The event listener and observer can be removed by:

    window.removeEventListener('resize', onResizeElem.checkForChanges);
    onResizeElem.observer.disconnect();
    

提交回复
热议问题