vue下轻松解决模拟微信视频缩略图拖拽→吸附窗口边界的功能

阅读 14

2022-12-22


 

 

<script>
export default {
data() {
return {
drag: {
draggedSel: ".girl", //被拖动元素的class或id
minY: 46 //顶部navBar的高度
}
};
},
created() {},
mounted() {
this.drag.draggedDiv = document.querySelector(this.drag.draggedSel);
this.drag.draggedDiv.addEventListener("touchstart", this.touchstart, {
passive: false
});
this.drag.draggedDiv.addEventListener("touchmove", this.touchmove, {
passive: false
});
this.drag.draggedDiv.addEventListener("touchend", this.touchend, {
passive: false
});
},
methods: {
// 实现移动端拖拽
touchstart() {
this.drag.draggedDiv.setAttribute("opacity", true); //透明度降低
var touch = event.touches ? event.touches[0] : event;
this.drag.cx = touch.clientX;
this.drag.cy = touch.clientY;
this.drag.x0 = this.drag.draggedDiv.offsetLeft; //记录初始左偏移量
this.drag.y0 = this.drag.draggedDiv.offsetTop; //记录初始上偏移量
},
touchmove() {
var touch = event.touches ? event.touches[0] : event;
//组织默认事件,防止body滑动
event.preventDefault();
this.drag.x1 = this.drag.x0 + (touch.clientX - this.drag.cx);
this.drag.y1 = this.drag.y0 + (touch.clientY - this.drag.cy);
this.drag.cw =
document.documentElement.clientWidth || document.body.clientWidth;
this.drag.ch =
document.documentElement.clientHeight || document.body.clientHeight;
this.drag.minX = 0;
this.drag.maxX = this.drag.cw - this.drag.draggedDiv.offsetWidth;
this.drag.maxY = this.drag.ch - this.drag.draggedDiv.offsetHeight;
//边界判断
this.drag.x1 =
this.drag.x1 < this.drag.minX ? this.drag.minX : this.drag.x1;
this.drag.x1 =
this.drag.x1 > this.drag.maxX ? this.drag.maxX : this.drag.x1;
this.drag.y1 =
this.drag.y1 < this.drag.minY ? this.drag.minY : this.drag.y1;
this.drag.y1 =
this.drag.y1 > this.drag.maxY ? this.drag.maxY : this.drag.y1;
this.drag.draggedDiv.style.left = this.drag.x1 + "px";
this.drag.draggedDiv.style.top = this.drag.y1 + "px";
},
touchend() {
this.drag.draggedDiv.removeAttribute("opacity"); //回复透明度
//吸附左右边界
var x = this.drag.x1 < this.drag.cw / 2 ? this.drag.minX : this.drag.maxX;
var y = this.drag.y1 < this.drag.ch / 2 ? this.drag.minY : this.drag.maxY;
var minxDis =
this.drag.x1 < this.drag.cw / 2
? this.drag.x1 - this.drag.minX
: this.drag.maxX - this.drag.x1;
var minyDis =
this.drag.y1 < this.drag.ch / 2
? this.drag.y1 - this.drag.minY
: this.drag.maxY - this.drag.y1;
if (minxDis < 50 || minyDis < 50) {
minxDis < minyDis
? (this.drag.draggedDiv.style.left = x + "px")
: (this.drag.draggedDiv.style.top = y + "px");
}
}
}
};
</script>


精彩评论(0)

0 0 举报