基于Vue实现拖拽效果 ,拿这个改了改
// customDrag.js
export default {
bind: function(el) {
let oDiv = el; // 获取当前元素
oDiv.style.cursor = 'grab'; // 初始设置为抓手样式
oDiv.onmousedown = (e) => {
// 鼠标按下,改变鼠标样式为抓取状态
oDiv.style.cursor = 'grabbing';
// 算出鼠标相对元素的位置
let disX = e.clientX - oDiv.offsetLeft;
let disY = e.clientY - oDiv.offsetTop;
document.onmousemove = (e) => {
// 用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
let left = e.clientX - disX;
let top = e.clientY - disY;
// 检查元素的新位置是否在边界内
if (left < 320) left = 340; // 左边界
if (top < 50) top = 50; // 上边界
if (left > window.innerWidth - oDiv.offsetWidth - 100) left = window.innerWidth - oDiv.offsetWidth - 50; // 右边界
if (top > window.innerHeight - oDiv.offsetHeight - 100) top = window.innerHeight - oDiv.offsetHeight - 50; // 下边界
oDiv.style.left = left + 'px';
oDiv.style.top = top + 'px';
};
document.onmouseup = (e) => {
// 鼠标抬起,改变鼠标样式回抓手状态
oDiv.style.cursor = 'grab';
document.onmousemove = null;
document.onmouseup = null;
}
}
}
}
注册
// directive/index.js
import customDrag from '@/directive/dialog/customDrag'
const install = function(Vue) {
Vue.directive('customDrag', customDrag)
}
export default install
main.js
import directive from './directive' // directive
Vue.use(directive)
使用
// a.vue
<div v-customDrag class="drag-box border-indigo-500 ">
弹窗内容
</div>
<style lang="scss" scoped>
.drag-box {
position:absolute;
top: 200px;
right:200px;
width:300px;
height:200px;
background: #fff;
border-radius: 5px;
box-shadow: 0 4px 12px rgba(0,0,0,.15);
z-index: 2;
}
</style>