我想在我听的块的宽度发生变化时调用我的代码。怎么样?
仅当窗口大小发生变化时才会调用 onresize
。
答案 0 :(得分:5)
正如您所提到的,页面上的元素没有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);
答案 1 :(得分:0)
当元素的宽度发生变化时,浏览器不会提供默认事件。但是,就像@Leo提到的那样,您可以注册并触发自己的活动。
您必须执行以下3个步骤:
示例代码在此处:
<body>
<div class="square"></div>
</body>
$(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);
});
您可以在此处查看CodePen Live Demo
答案 2 :(得分:0)
可以选择使用ResizeObserver:
观察所有宽度的变化,当MutationObserver
不同于无用代码的answer时。
但是,浏览器兼容性不强。
JS :
var foo = document.getElementById('foo');
var observer = new window.ResizeObserver(entries =>
console.log(entries[0].contentRect.width));
observer.observe(foo);
}