vue中拖拽块级元素
主要用到的以下的触发事件
- mousedown()
- mousemove()
- mouseup()
分别处理的事件
- mousedown():
- 判断鼠标是否压下
- 获取压下时的鼠标坐标
- mousemove():
- 获取当前鼠标坐标,
- 计算得到位移量并计算出新的坐标(更新坐标)
- 向块级元素传值对块级元素进行显示
- 更新当前坐标(连续拖拽可以视为前一次move的结束点为下一次的起始点)
- mouseup():
- 记录鼠标压下状态
Coding
<template>
<div style="position: absolute;
top: 0px;left: 0px;
height: 500px;width: 500px;
background-color: #5C5C5C;"
@mousedown="_MouseDown"
@mousemove="_MouseMove"
@mouseup="_MouseUp"
id="ShowBox">
<div
style="position: absolute;
top: 0px;left: 0px;"
ref="refMap">
</div>
</div>
<template>
<script>
const iMapWidth = 800;
const iShowViewWidth = 500;
export default(
data() {
return{
bMouseDown:false,
iLastMouseDownX:0,
iLastMouseDownY:0,
iShowMapTop:0,
iShowMapLeft:0,
}
},
methods:{
_MouseDown(e)
{
this.bMouseDown = true;
this.iLastMouseDownX = e.clientX;
this.iLastMouseDownY = e.clientY;
},
_MouseMove(e)
{
if(this.bMouseDown)
{
let iMoveX = this.iLastMouseDownX - e.clientX;
let iMoveY = this.iLastMouseDownY - e.clientY;
this.iShowMapTop -= iMoveY;
this.iShowMapLeft -= iMoveX;
this.iLastMouseDownX = e.clientX;
this.iLastMouseDownY = e.clientY;
if(this.iShowMapLeft >= 0)
{
this.iShowMapLeft = 0;
}
if(this.iShowMapLeft >= 0)
{
this.iShowMapLeft = 0;
}
if(this.iShowMapLeft <= iShowViewWidth - iMapWidth)
{
this.iShowMapLeft = iShowViewWidth - iMapWidth;
}
if(this.iShowMapTop >= 0)
{
this.iShowMapTop = 0;
}
this._DisplayMap(this.iShowMapTop,this.iShowMapLeft)
}
else
{
return;
}
},
_MouseUp()
{
this.bMouseDown = false;
},
_DisplayMap(iTop,iLeft)
{
this.$refs.refMap.style.top = iTop + 'px';
this.$refs.refMap.style.left = iLeft + 'px';
}
},
)
</script>
<style>
#ShowBox {
overflow-y: hidden;
overflow-x: hidden;
background-color: none;
}
div
{
-webkit-user-select: none;
-moz-user-select: none;
-o-user-select: none;
-ms-user-select: none;
user-select: none
}
</style>
浏览器预览效果
(做了边际限制,视频中只能拖拽一定范围,可以按照实际需要去更改显示范围)
注意点
如果不加上style中有关div选中状态禁用的内容,可能会出现拖拽时光标禁用的样式。
会抓不到mouseup事件,加上比较好。