当使用自定义指定 v-div-drag时,发现需要监听div的offsetTop和offsetLeft来控制父级box的样式
div实现可拖拽效果(类似el-dialog拖动)_爱吃泡芙啊的博客-CSDN博客
完整代码:
<div ref="treeBox" v-div-drag class="tree-box" v-if="showTree">
<carsTree ref="carsTree" :restaurants="restaurants" />
</div>
data() {
return {
showTree: false, // 是否展示树结构的标志
targetOffsetLeft: 0, // dom 距离文档左侧的值
targetOffsetTop: 0, // dom 距离文档顶部的值
observer: null,
}
}
// methods
showCarsTree() {
this.showTree = true
if (this.showTree) {
this.$nextTick(() => {
this.getTargetOffsetLeftAndTop();
this.initObserver();
})
} else {
this.observer.disconnect();
}
},
/**
* @Event 方法
* @description: 初始化offsetLeft 和 offsetTop
* */
getTargetOffsetLeftAndTop() {
const target = this.$refs.treeBox;
this.targetOffsetLeft = target.offsetLeft;
this.targetOffsetTop = target.offsetTop;
console.log(this.targetOffsetLeft)
console.log(this.targetOffsetTop)
},
/**
* @Event 方法
* @description: 监听左侧显示隐藏的树的位置变化
* */
initObserver() {
const target = this.$refs.treeBox;
this.observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
if (mutation.attributeName === 'style') {
const newOffsetLeft = target.offsetLeft;
const newOffsetTop = target.offsetTop;
/* 当元素距离文档左侧或者顶部的值变化时 */
if (newOffsetLeft !== this.targetOffsetLeft) {
this.targetOffsetLeft = newOffsetLeft;
console.log('offsetLeft变化了:', this.targetOffsetLeft);
/* doSomething */
}
if (newOffsetTop !== this.targetOffsetTop) {
this.targetOffsetTop = newOffsetTop;
console.log('offsetTop变化了:', this.targetOffsetTop);
/* doSomething */
}
}
});
});
this.observer.observe(target, { attributes: true, attributeFilter: ['style'], attributeOldValue: true });
},
close() {
this.showTree = false;
},