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

后端 未结 3 1176
没有蜡笔的小新
没有蜡笔的小新 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条回答
  •  梦毁少年i
    2021-01-13 13:35

    There's no default event provided by browser when the width of your element is changing. However, just like @Leo mentioned, you can register and trigger your own event.

    There are 3 steps you have to:

    1. Register a custom event
    2. Bind your element with the custom event
    3. Trigger the event when you resize the element

    The sample code is here:

    HTML

    
      

    JS

    $(function() {
      var $square = $('.square');
    
      // Register a custom event and bind an event handler on it
      $square.on('square.resize', function() {
        console.log('Square is resized!');
      });    
    
      // Trigger that event when you change the square size
      function resizeSquare() {
        $square.width($square.width() + 10);
        $square.height($square.height() + 10);
        $square.trigger('square.resize');
      }
    
      // Anytime you resize the square, it will trigger 'square.resize' event
      // In this example, I am using setInverval() to resize the square, but you could
      // change it into any ways you like
      setInterval(resizeSquare, 1000);
    
    });
    

    You may check here for CodePen Live Demo

提交回复
热议问题