前言
原生js事件实现拖拽
实例
<template>
<div class="drag-content" ref="dragContent">
<div class="div-drag" @mousedown="tagDraggable($event)"></div>
</div>
</template>
<script>
export default {
name: '',
data () {
return {
}
},
components: {},
props: {},
computed: {},
methods: {
// 标签拖拽
tagDraggable (e) {
// 获取目标元素
e = e || window.event
let odiv = e.target;
if (!odiv.className.includes('div-drag')) return
// 算出鼠标相对元素的位置
let disX = e.clientX - odiv.offsetLeft;
let disY = e.clientY - odiv.offsetTop;
if (e.preventDefault) {
e.preventDefault()
} else {
e.returnValue = false
}
document.onmousemove = (e) => { //鼠标按下并移动的事件
// 用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
e = e || window.event
let left = e.clientX - disX;
let top = e.clientY - disY;
let width = this.$refs.dragContent.offsetWidth
let height = this.$refs.dragContent.offsetHeight
// 标签不能移动到容器外
left < 0 && (left = 0)
left > width && (left = width - odiv.offsetWidth)
top < 0 && (top = 0)
top > height && (top = height - odiv.offsetHeight)
// 移动当前元素
odiv.style.left = `${left}px`;
odiv.style.top = `${top}px`;
}
document.onmouseup = (e) => {
document.onmousemove = null;
document.onmouseup = null;
};
}
},
created () {
},
beforeMount () {
},
mounted () {
},
watch: {},
}
</script>
<style lang='less' scoped>
.drag-content {
position: relative;
width: 500px;
height: 500px;
margin: auto;
border: 1px dashed red;
}
.div-drag {
position: absolute;
width: 60px;
height: 60px;
background: red;
cursor: move;
}
</style>