简介:
利用 MutationObserver 监听用户拖动textarea高度变化,实现修改对应div,使二者高度同步。
如图所示:
源码(复制另存txt,修改.html直接运行)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>监听div、textarea高度变化执行某个操作 - Vue Element Textarea</title>
<!-- 引入样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<style>
.fu{
display: flex;
background: rgb(92, 62, 62);
height: 500px;
width: 80%;
margin: 0px auto;
padding: 20px;
}
.fu .left{
border: 1px solid #eee;
background: #fff;
height: 64px;
font-size: 14px;
border-radius: 4px;
padding: 5px 10px;
box-sizing: border-box;
}
.fu .right{
flex: 1;
margin-left: 10px;
height: max-content;
}
</style>
</head>
<body style="background: #eee;">
<div id="app">
<div class="fu">
<div ref='left' class="left">什么!<br/>我竟然会动</div>
<el-input ref='right' class="right" size="mini" v-model="txt" type="textarea" :autosize="{ minRows: 3}"></el-input>
</div>
</div>
</body>
<script src="https://lib.baomitu.com/vue/2.6.14/vue.min.js"></script>
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
let time = ''
new Vue({
el: '#app',
data() {
return {
txt:'我是被监控的文本输入框,请右下角拖动我'
}
},
mounted(){
const MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver
//需要监控的div
const divBox = this.$refs.right.$el
//监控div的动态高度
let height = ''
//配置选项
const config = { attributes: true, childList: false, subtree: true, attributeFilter:['style'],attributeOldValue:true };
const observer = new MutationObserver( (mutationsList, observer) => {
// for (let mutation of mutationsList) {
// if (mutation.type == 'childList') {
// console.log('子元素被修改');
// }
// if (mutation.type == 'attributes') {
// console.log(mutation.attributeName + '属性被修改');
// }
// }
height = getComputedStyle(divBox).getPropertyValue('height')
// 防抖 start
// if(time){
// window.clearTimeout(time)
// tiem = ''
// }
// time = setTimeout(()=>{
// this.$refs.left.style.height = height
// },500)
// 防抖 end
// 节流 start
if(!time){
time = setTimeout(()=>{
this.$refs.left.style.height = height
window.clearTimeout(time)
tiem = ''
},500)
}
// 节流 end
});
//开始观测
observer.observe(divBox, config);
//停止观测
// observer.disconnect();
// observer.takeRecords()
},
methods: {
}
})
</script>
</html>