Javascript 当块';宽度改变了吗?
我想在我侦听的块的宽度改变时调用我的代码。怎么做Javascript 当块';宽度改变了吗?,javascript,html,Javascript,Html,我想在我侦听的块的宽度改变时调用我的代码。怎么做 onresize仅在窗口大小更改时调用。当元素宽度更改时,浏览器不提供默认事件。但是,正如前面提到的,您可以注册并触发自己的事件 您必须执行以下三个步骤: 注册自定义事件 用自定义事件绑定元素 在调整元素大小时触发事件 示例代码如下: HTML 您可以在此处查看,正如您所提到的,页面上的元素没有调整大小的事件,仅用于 但是,您可以使用来检测元素中的更改: const foo=document.querySelector('#foo'); 让ol
onresize
仅在窗口大小更改时调用。当元素宽度更改时,浏览器不提供默认事件。但是,正如前面提到的,您可以注册并触发自己的事件
您必须执行以下三个步骤:
您可以在此处查看,正如您所提到的,页面上的元素没有调整大小的事件,仅用于 但是,您可以使用来检测元素中的更改:
const foo=document.querySelector('#foo');
让oldWidth=window.getComputedStyle(foo.getPropertyValue('width');
常量观察者=新的突变观察者(功能(突变){
突变。forEach(突变=>{
if(mutation.target==foo&&
mutation.attributeName==='style'&&
oldWidth!==foo.style.width){
foo.textContent='Width changed from'+
oldWidth+'到'+foo.style.width;
oldWidth=foo.style.width;
}
});
});
//配置观察者,只需查看属性更改:
常量配置={
属性:true
};
//开始观察
observer.observe(foo,config);
//请在一秒钟后更改宽度,以便我们可以检测到它
设置超时(()=>{
foo.style.width='150px';
}, 1000);代码>
#foo{
边框:2px实心#f30;
宽度:100px;
高度:100px;
过渡:宽度1s;
}
foo
可以使用以下选项:
观察所有宽度的变化,当MutationObserver
不象无用代码那样
但是,它没有太多的浏览器兼容性
JS:
var foo = document.getElementById('foo');
var observer = new window.ResizeObserver(entries =>
console.log(entries[0].contentRect.width));
observer.observe(foo);
}
是什么导致它发生变化?答案是不,不,没有。但您可以定义自定义事件。MutationObserver不观察css类引起的宽度更改。虽然可以观察到类本身的变化,但影响元素大小的类可以添加到元素本身以外的元素中。下面添加的答案适用于css类引起的宽度变化。请参阅使用Back当我最初编写答案时,ResizeObserver
不存在。截至2020年8月,这一数字有所下降。
$(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);
});
var foo = document.getElementById('foo');
var observer = new window.ResizeObserver(entries =>
console.log(entries[0].contentRect.width));
observer.observe(foo);
}