How to detect DIV's dimension changed?

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

    var div = document.getElementById('div');
    div.addEventListener('resize', (event) => console.log(event.detail));
    
    function checkResize (mutations) {
        var el = mutations[0].target;
        var w = el.clientWidth;
        var h = el.clientHeight;
        
        var isChange = mutations
          .map((m) => m.oldValue + '')
          .some((prev) => prev.indexOf('width: ' + w + 'px') == -1 || prev.indexOf('height: ' + h + 'px') == -1);
    
        if (!isChange)
          return;
    
        var event = new CustomEvent('resize', {detail: {width: w, height: h}});
        el.dispatchEvent(event);
    }
    
    var observer = new MutationObserver(checkResize); 
    observer.observe(div, {attributes: true, attributeOldValue: true, attributeFilter: ['style']});
    #div {width: 100px; border: 1px solid #bbb; resize: both; overflow: hidden;}
    DIV

提交回复
热议问题