拖动前:
拖动后:
实现原理
html中使用变量充当元素的高度,然后使用vue的directives创建一个自定的绑定事件,在绑定事件中使用onmousedown来给鼠标点击时间绑定一个计算鼠标滑动距离的方法。将获取的距离修改到变量中改变元素高度。
HTML代码
// 这是一个拖动的指标 v-drag是一个自定义的vue事件
<div v-drag class="icon" />
// 这是通过拖动改变的div元素
<div class="box" :style="'height: '+ boxHeight + 'px;'"/>
js代码
//
<script>
export default {
directives: {
drag: {
inserted(el, binding, vNode) {
el.style.cursor = 'n-resize'
const that = vNode.context
document.addEventListener('selectstart', function(e) {
e.preventDefault() // 阻止滑动时选中文本
})
el.onmousedown = function(e) {
var Y = e.clientY // 获取初始的坐标
document.onmousemove = function(e) {
const H = e.clientY - Y // 计算鼠标移动距离
const Height = that.boxHeight - H // 初始高度加上鼠标移动距离
if (Height <= 200 || Height >= 400) return // 设置最高和最低高度
that.boxHeight = Height // 修改元素高度
Y = e.clientY // 实时更新原始对照坐标用来同步鼠标和元素真实距离
}
// 防止继续执行
document.onmouseup = function() {
document.onmousemove = document.onmousedown = null
}
}
}
}
},
data() {
return {
boxHeight: 260
}
},
}
</script>