组件可拖拽,指令
v-drag
封装在drag.js
代码:
// 拖拽指令
const drag = {
bind: function(el, binding, vnode, oldVnode) {
let firstTime='',lastTime='';
const headerElement = el.querySelector('.drag');
// 获取原有CSS属性
const elementStyle = window.getComputedStyle(el);
headerElement.onmousedown = e => {
// 鼠标按下,计算当前元素距离可视区的距离
const disX = e.clientX - headerElement.offsetLeft;
const disY = e.clientY - headerElement.offsetTop;
// 获取left和top的值
const leftValue = parseFloat(elementStyle.left);
const topValue = parseFloat(elementStyle.top);
el.setAttribute('data-flag',false)
firstTime = new Date().getTime();
document.onmousemove = function(e) {
// 通过事件委托,计算移动的距离
const moveLeft = e.clientX - disX;
const moveTop = e.clientY - disY;
const { clientWidth, clientHeight } = el.parentNode;
// 确定移动边界
const [minLeft, maxLeft] = [0, clientWidth - parseFloat(elementStyle.width)]
const [minTop, maxTop] = [0, clientHeight - parseFloat(elementStyle.height)]
const resultLeft = leftValue + moveLeft > maxLeft ? maxLeft : Math.max(...[minLeft, leftValue + moveLeft])
const resultTop = topValue + moveTop > maxTop ? maxTop : Math.max(...[minTop, topValue + moveTop])
// 移动当前元素
el.style.left = `${resultLeft}px`;
el.style.top = `${resultTop}px`;
el.style.transform = 'none';
};
document.onmouseup = function(e) {
document.onmousemove = null;
document.onmouseup = null;
//判断元素是否为点击事件
lastTime = new Date().getTime();
if( (lastTime - firstTime) < 200){
el.setAttribute('data-flag',true)
}
};
};
},
};
export default { drag };
使用:
<template>
<div class="chat" id="chat" v-if="isShowNewsModule">
<div class="chat-wrap" v-drag ref="chatWrap">
<div class="news-header drag">
<span>消息</span>
<Icon
class="close-icon"
icon="close"
size="20px"
@click="closeModule"
/>
</div>
<div class="news-body">
<ChatList></ChatList>
<ChatInfo></ChatInfo>
</div>
</div>
</div>
</template>
这里id 为chat的元素是父元素 ,也就是你的组件只能在这个元素的区域内拖拽,v-drag绑定在需拖拽的元素上,.drag绑定在组件内需拖拽的元素上,比如我这里只需要按住组件内的头部header就能拖动整个组件,按住组件内其他地方不拖拽,所以把.drag放在header上。
不过另外还有一种可能就是需要长按组件的任意一处都能拖拽组件,这样的话.drag就放在组件最外层,但是会有个问题,就是拖拽指令会和点击事件冲突,如果组件内需要处理点击事件的话就会有问题,所以我在指令里加上了
let firstTime='',lastTime='';
...
el.setAttribute('data-flag',false)
firstTime = new Date().getTime();
...
//判断元素是否为点击事件
lastTime = new Date().getTime();
if( (lastTime - firstTime) < 200){
el.setAttribute('data-flag',true)
}
在mouseup的时候判断事件间隔,大于200则为拖拽 小于200是点击事件,
再在组件的点击事件里判断就行了
//点击事件
openPage () {
let isClick = this.$refs.hostTask.getAttribute('data-flag')
if(isClick !== 'true') { //如果是拖拽就return掉
return false
}
//点击事件需处理的事情
dosomething...
},
总结:在做之前一定需要弄懂 offsetLeft ,offsetWidth ,clientX,top 这些概念 不然像我一样一开始晕晕乎乎即使在百度上查到代码也不能弄透,弄懂之后理解起来就容易许多。
ps:又是获取到新知识的一天,开心!