拖拽球
拖拽球vue組件代碼:
<template>
<div
:style="{right: right}"
class="drag-it-dude"
@mousedown.stop="hang"
@mouseup.stop="drop"
>
<slot name="content"></slot>
<slot name="plus"></slot>
<slot name="minus"></slot>
<slot name="close"></slot>
</div>
</template>
<script>
export default {
name: 'drag-it-dude',
props: {
parentWidth: {
type: Number,
default: 0,
},
parentHeight: {
type: Number,
default: 0,
},
right: {
type: String,
default: '0px',
},
},
data: () => ({
shiftY: null,
shiftX: null,
left: 0,
top: 0,
elem: null,
parent: {
width: 0,
height: 0,
},
}),
methods: {
elementMove(e) {
this.$emit('dragging');
e.preventDefault();
if (!e.pageX) {
document.body.style.overflow = 'hidden';
}
const x = e.pageX || e.changedTouches[0].pageX;
const y = e.pageY || e.changedTouches[0].pageY;
let newLeft = x - this.shiftX;
let newTop = y - this.shiftY;
const newRight = x - this.shiftX + this.elem.offsetWidth;
const newBottom = y - this.shiftY + this.elem.offsetHeight;
if (newLeft < 0) {
newLeft = 0;
} else if (newRight > this.parent.width) {
newLeft = this.parent.width - this.elem.offsetWidth;
} else {
newLeft = x - this.shiftX;
}
if (newTop < 0) {
newTop = 0;
} else if (newBottom > this.parent.height) {
newTop = this.parent.height - this.elem.offsetHeight;
} else {
newTop = y - this.shiftY;
}
this.elem.style.left = `${newLeft}px`;
this.left = newLeft;
this.elem.style.top = `${newTop}px`;
this.top = newTop;
},
hang(e) {
this.$emit('activated');
this.parent.width = this.parentWidth || this.elem.parentNode.offsetWidth;
this.parent.height = this.parentHeight || this.elem.parentNode.offsetHeight;
this.shiftX = e.pageX
? e.pageX - this.elem.offsetLeft
: e.changedTouches[0].pageX - this.elem.offsetLeft;
this.shiftY = e.pageY
? e.pageY - this.elem.offsetTop
: e.changedTouches[0].pageY - this.elem.offsetTop;
if (e.pageX) {
this.elem.addEventListener('mousemove', this.elementMove);
this.elem.addEventListener('mouseleave', this.drop);
}
},
drop() {
this.$emit('dropped');
document.body.style.overflow = null;
this.elem.removeEventListener('mousemove', this.elementMove, false);
this.elem.onmouseup = null;
this.elem.ontouchend = null;
},
},
mounted() {
this.elem = this.$el;
},
};
</script>
<style>
.drag-it-dude {
position: absolute;
top: 0;
right: 0;
z-index: 1;
font-size: 12px;
cursor: move;
}
</style>
拖拽球vue組件使用:
<drag-it-dude right="20px">
<div class="ball"></div>
</drag-it-dude>