- 例子1:拖住div移动位置
第一步,创建draggable.ts文件
const draggable = {
// 指令绑定到元素
bind(el: any, binding: any) {
/*
* el 指令绑定的元素,可以用来直接操作dom
* binding 一个对象,包含许多的属性
*/
el.style.cursor = 'move'
el.onmousedown = function (e: any) {
console.log('开始拖动')
const disX = e.clientX - el.offsetLeft
const disY = e.clientY - el.offsetTop
document.onmousemove = function (e) {
console.log('拖动中')
el.style.left = e.clientX - disX + 'px'
el.style.top = e.clientY - disY + 'px'
}
document.onmouseup = function () {
document.onmousemove = null
console.log('拖动结束')
}
return false
}
}
}
export default draggable
第二步,在需要的vue组件中,注册指令,也可全局注册
<script lang="ts">
import draggable from '/draggable.ts'
import { Vue, Component, Watch } from 'vue-property-decorator'
Vue.directive('draggable', draggable)
</script>
第三步,绑定指令
<div id="maskDiv" v-draggable />
- 例子2:拖动块改变div宽度
第一步,创建changWidthByDrag.ts文件
const changWidthByDrag = {
// 指令绑定到元素
bind(el: any, binding: any) {
/*
* el 指令绑定的元素,可以用来直接操作dom
* binding 一个对象,包含许多的属性
*/
el.onmousedown = function (e: any) {
// console.log('开始拖动')
// 这个是移动的范围元素
const parent: any = document.getElementById('main')
// 计算移动元素最大可移动的left、top,限制其移除框外
const maxWidth = parent.offsetWidth - 70
const disX = e.clientX
// 这个是要改变宽度的div
const targetDiv: any = document.getElementById('rightPanel')
const startWidth: number = targetDiv.offsetWidth
document.onmousemove = function (e: any) {
// console.log('拖动中')
let w = disX - e.clientX + startWidth
// 保证不低于最小宽度320px
if (w < 320) w = 320
// 保证不超出父div宽度
if (w > maxWidth) w = maxWidth
targetDiv.style.width = w + 'px'
}
document.onmouseup = function () {
document.onmousemove = null
// console.log('拖动结束')
}
return false
}
}
}
export default changWidthByDrag
第二步,在需要的vue组件中,注册指令,也可全局注册
<script lang="ts">
import changWidthByDragfrom '/changWidthByDrag.ts'
import { Vue, Component, Watch } from 'vue-property-decorator'
Vue.directive('changWidthByDrag', changWidthByDrag)
</script>
第三步,绑定指令
// 最大宽度的div
<div id="main">
// 要改变宽度的div
<div class="widget-panels">
// 拖动的div
<div class="chang-width-block" v-changWidthByDrag />
</div>
</div>
// css
#main {
width:100vh;
padding:15px;
}
.widget-panels {
right: 20px;
top: 55px;
position: absolute;
.chang-width-block {
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 5px;
// background: yellow;
cursor: e-resize;
z-index: 999999;
}
}