其实在 监听 变化的 可能童鞋们首先 想到的就是 resize 事件 但问题是这个方法 好像只能在 window 那个上面使用
放在元素上不管用 可以去试试看 哈
先上效果图吧
其实 改变元素的 宽高变化 可以 通过jquery的动画 方法来实现 animate 第三个参数就是 动画完成 之后 触发的回调函数
<style type="text/css">
.parent {
position: relative;
margin: 0 auto;
width: 40%;
height: 500px;
border: 1px solid #f00;
}
</style>
<div class="parent">
</div>
而监听 dom宽度变化的 则是 MutationObserver 方法
let status = true;
// 选择需要观察变动的节点
const targetNode = document.querySelector('.parent');
// 观察器的配置(需要观察什么变动)
const config = { attributes: true, childList: false, subtree: false };
// 当观察到变动时执行的回调函数
const callback = function(mutationsList, observer) {
// Use traditional 'for loops' for IE 11
for(let mutation of mutationsList) {
if (mutation.type === 'childList') {
console.log('A child node has been added or removed.');
}
else if (mutation.type === 'attributes') {
if(status) {
console.log('我在慢慢变长');
} else {
console.log('我在慢慢变短');
}
}
}
};
// 创建一个观察器实例并传入回调函数
const observer = new MutationObserver(callback);
// 以上述配置开始观察目标节点
observer.observe(targetNode, config);
// 之后,可停止观察
// observer.disconnect();
var isFlag = true;
$('button').click(function() {
if(isFlag) {
$('.parent').animate({"height" : '800px'}, 'slow', function() {
status = false;
console.log('变长了');
})
isFlag = false;
} else {
$('.parent').animate({"height" : '500px'}, 'slow', function() {
status = true;
console.log('变短了')
})
isFlag = true;
}
})
关注我 持续更新 前端 知识