How to detect DIV's dimension changed?

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

    I DO NOT recommend setTimeout() hack as it slows down the performance! Instead, you can use DOM mutation observers for listening to Div size change.

    JS:

    var observer = new MutationObserver(function(mutations) {
        console.log('size changed!');
      });
      var target = document.querySelector('.mydiv');
      observer.observe(target, {
        attributes: true
      });
    

    HTML:

    Here's the fiddle
    Try to change the div size.


    You can further wrap your method in the debounce method to improve efficiency. debounce will trigger your method every x milliseconds instead of triggering every millisecond the DIV is being resized.

提交回复
热议问题