不知道看的哪位大佬的代码,改了改适合自己的需求,想着记录一下,以后直接copy。
组件内定义一个指令:
因为我的是要保持靠近顶部,且只能左右滑动,所以我把顶部的赋值去掉了。
directives: {
drag: {
bind: function (el, binding, vnode) {
const odiv = el
let firstTime = ''
let lastTime = ''
odiv.onmousedown = (e) => {
const disX = e.clientX - odiv.offsetLeft
// const disY = e.clientY - odiv.offsetTop
firstTime = new Date().getTime()
document.onmousemove = (e) => {
let left = e.clientX - disX
// const top = e.clientY - disY
// vnode.context.positionX = top
vnode.context.positionY = left
const screenWidth = window.innerWidth - 50
// 判断不超出边界
if (left < 0) {
left = 0
} else if (left > screenWidth) {
left = screenWidth
}
odiv.style.left = left + 'px'
// odiv.style.top = top + 'px'
}
document.onmouseup = () => {
document.onmousemove = null
document.onmouseup = null
lastTime = new Date().getTime()
// 解决拖拽和点击事件冲突
if (lastTime - firstTime < 200) {
console.log('click')
}
}
}
}
}
}
使用:
<template>
<div
class="top-float-button"
:style="moveStyle"
v-drag
>
<img src="./../../assets/floatImg.png" />
<span>测试</span>
</div>
</template>
网友评论