Is there a event invoked when a block's width changes?

后端 未结 3 1083
没有蜡笔的小新
没有蜡笔的小新 2021-01-13 13:04

I want to call my code when the width of the block I listen to changes. How to?

onresize is invoked only when the size of the window changes.

3条回答
  •  时光说笑
    2021-01-13 13:31

    An option can be to use ResizeObserver:

    Observes all width changes, wen when MutationObserver doesn't as in Useless Code's answer.

    Does not have much browser compatibility, however.

    JS:

    var foo = document.getElementById('foo');
    
    var observer = new window.ResizeObserver(entries => 
       console.log(entries[0].contentRect.width));
    
       observer.observe(foo);
    }
    

    Stackblitz in Angular

提交回复
热议问题