JavaScript window resize event

前端 未结 13 778
余生分开走
余生分开走 2020-11-22 00:58

How can I hook into a browser window resize event?

There\'s a jQuery way of listening for resize events but I would prefer not to bring it into my project for just t

13条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 01:13

    Solution for 2018+:

    You should use ResizeObserver. It is a browser-native solution that has a much better performance than to use the resize event. In addition, it not only supports the event on the document but also on arbitrary elements.

    var ro = new ResizeObserver( entries => {
      for (let entry of entries) {
        const cr = entry.contentRect;
        console.log('Element:', entry.target);
        console.log(`Element size: ${cr.width}px x ${cr.height}px`);
        console.log(`Element padding: ${cr.top}px ; ${cr.left}px`);
      }
    });
    
    // Observe one or multiple elements
    ro.observe(someElement);
    

    Currently, Firefox, Chrome, and Safari support it. For other (and older) browsers you have to use a polyfill.

提交回复
热议问题