<template>
<div ref="box" class="box">
<div id="handle" ref="handle" draggable="false" @mousedown="handleMousedown" />
</div>
</template>
<script>
export default {
name: 'Drag',
data() {
return {
disX: 0,
disY: 0,
down: false
}
},
mounted() {
document.addEventListener('mouseup', () => {
this.down = false
document.onmousemove = null
document.onmousedown = null
document.onmouseup = null
})
document.addEventListener('mousemove', (e) => {
// 获取鼠标的实时位置
const curX = e.clientX
const curY = e.clientY
// 获取拖拽的长度
const increaseX = curX - this.disX
const increaseY = curY - this.disY
// 按下开始拖拽改变目标元素大小
if (this.down) {
const width = this.$refs.handle.offsetWidth + increaseX
const height = this.$refs.handle.offsetHeight + increaseY
width < 200 ? (this.$refs.box.style.width = '200px') : (this.$refs.box.style.width = width + 'px')
height < 200 ? (this.$refs.box.style.height = '200px') : (this.$refs.box.style.height = height + 'px')
}
})
},
methods: {
// down置为true,记录鼠标点下的位置
handleMousedown(e) {
this.down = true
this.disX = e.clientX - this.$refs.handle.offsetLeft
this.disY = e.clientY - this.$refs.handle.offsetTop
}
}
}
</script>
<style scoped>
.box {
width: 200px;
height: 200px;
background-color:#000;
margin: 0 auto;
margin-top: 100px;
position: relative;
}
#handle {
width: 20px;
height: 20px;
background-color: red;
position: absolute;
right: 0;
bottom: 0;
-webkit-user-select: none;
-moz-user-select: none;
-o-user-select: none;
user-select: none;
cursor: se-resize;
}
</style>
限制最小缩放尺寸是宽高200px