9
14

More than 3 years have passed since last update.

div のリサイズイベントを拾う方法(メモ)

Last updated at Posted at 2020-06-12

div のリサイズを拾う方法のメモ。
resizeイベントは、divなどの要素では発火しません。。。windowのリサイズなら発火するのですが。。。
そこで、要素のリサイズ時にイベントを拾う方法を調べてみたら、以下のページが見つかりました。参考にさせていただきました!

参考
Divタグのresizeイベントを拾うには - souki-paranoiastのブログ https://souki-paranoiast.hatenablog.com/entry/2018/12/08/231152

resize.html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>test</title>

  <style type="text/css" scoped>
    #resizeable{
      border: solid 3px;
      border-color: blue;
      width: 100px;
      height: 100px;
      overflow: auto;
      resize: both;
    }
  </style>
</head>

<body>
  <h1>リサイズサンプル</h1>
  <div id="main">
    <div>
      <div id="resizeable"></div>
    </div>
  </div>
  <script>
    //イベント登録
    document.addEventListener('DOMContentLoaded', () => {
      //要素のリサイズイベント取得
      const observer = new MutationObserver(() => {
        const resizeable = document.getElementById('resizeable')
        //要素のサイズ確認
        const width = resizeable.getBoundingClientRect().width
        const height = resizeable.getBoundingClientRect().height
        console.log('size(w,h): ', width, height)
      })
      observer.observe(resizeable, {
        attriblutes: true,
        attributeFilter: ["style"]
      })
    }, false)
  </script>

</body>

</html>

なるほど。Observerを使えばよかったのね。参考になりました!ありがとうございます m(_ _)m

2020-06-12 (1).png
2020-06-12 (2).png

9
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
14