聞くブロックの幅が変わったときにコードを呼び出したい。方法?
onresize
ウィンドウのサイズが変更された場合にのみ呼び出されます。
あなたが言ったようresize
に、ページ上の要素のイベントはありませんwindow
。
ただし、Mutation Observersを使用して、要素の変更を検出できます。
var foo = document.querySelector('#foo'),
oldWidth = foo.style.width,
observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.target === foo && mutation.attributeName === 'style' &&
oldWidth !== foo.style.width) {
console.log('Width Changed!');
oldWidth = foo.style.width;
}
});
});
// configuration of the observer, just look for attribute changes:
var config = {
attributes: true
};
observer.observe(foo, config);
もう少し作業を行うことで、幅の変化を検出する要素にカスタムイベントを追加する関数を作成できます。
var addWidthChangeEvent = function (element) {
var oldWidth = foo.style.width,
observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.target === element && mutation.attributeName === 'style' &&
oldWidth !== element.style.width) {
oldWidth = foo.style.width;
element.dispatchEvent(new Event('widthChange'));
}
});
});
// configuration of the observer, just look for attribute changes:
var config = {
attributes: true
};
observer.observe(element, config);
}
var foo = document.getElementById('foo');
// create the custom event observer
addWidthChangeEvent(foo);
// you can now use addEventListener or jQuery to react
// to 'widthChange' events
foo.addEventListener('widthChange', function (event) {
// every time the width changes the text inside the box will
// be changed to the new width
foo.textContent = foo.style.width;
}, false);
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加