块的宽度更改时是否会调用事件? [英] Is there a event invoked when a block's width changes?

查看:57
本文介绍了块的宽度更改时是否会调用事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我听的块的宽度改变时,我想调用我的代码.怎么做?

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

onresize仅在窗口大小改变时被调用.

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

推荐答案

正如您提到的,页面上的元素没有resize事件,仅针对

As you mentioned, there is no resize event for elements on the page, just for window.

不过,您可以使用突变观察者来检测更改在一个元素中:

You can however use Mutation Observers to detect changes in an element:

const foo = document.querySelector('#foo');

let oldWidth =  window.getComputedStyle(foo).getPropertyValue('width');
const observer = new MutationObserver(function(mutations) {
  mutations.forEach(mutation => {
    if (mutation.target === foo &&
      mutation.attributeName === 'style' &&
      oldWidth !== foo.style.width) {
        foo.textContent = 'Width changed from ' +
          oldWidth + ' to ' + foo.style.width;
        oldWidth = foo.style.width;
    }
  });
});

// configure the observer, just look for attribute changes:
const config = {
  attributes: true
};

// start observing
observer.observe(foo, config);

// change the width after a second so we can detect it
setTimeout(() => {
  foo.style.width = '150px';
}, 1000);

#foo {
  border: 2px solid #f30;
  width: 100px;
  height: 100px;
  transition: width 1s;
}

<div id="foo">foo</div>

再做一些工作,您可以创建一个函数,该函数将自定义事件添加到要检测宽度变化的元素上:

With a little more work you can create a function that will add a custom event to the element you want to detect width changes on:

const addWidthChangeEvent = function(element) {
  let oldWidth =  window.getComputedStyle(element).getPropertyValue('width');
  const observer = new MutationObserver(mutations => {
    mutations.forEach(mutation => {
      if (mutation.target === element &&
        mutation.attributeName === 'style' &&
        oldWidth !== element.style.width) {
          oldWidth = element.style.width;
          element.dispatchEvent(new Event('widthChange'));
      }
    });
  });

  // configure the observer, just look for attribute changes:
  const config = {
    attributes: true
  };

  observer.observe(element, config);
};

const foo = document.getElementById('foo');

// add the new widthChange event to foo
addWidthChangeEvent(foo);

// add a listener for the new event
foo.addEventListener('widthChange', event => {
  foo.textContent = foo.style.width;
}, false);


const randomInt = (min, max) => {
  return Math.floor(Math.random() * (max - min + 1)) + min;
};

// change the width every 2 seconds
setInterval(() => {
  let newWidth = randomInt(4, 30) * 10;
  foo.style.width = newWidth + 'px';
}, 2000);

#foo {
  border: 2px solid #f30;
  width: 100px;
  height: 100px;
  transition: width 1s;
}

<div id="foo">foo</div>

这篇关于块的宽度更改时是否会调用事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆