如何给vue项目里面写拖拽悬浮小图标呢
首先
1、html文件 一定要给父盒子一个ID
<div
class="xuanfu"
id="moveDiv"
@mousedown="down()"
@touchstart="down()"
@mousemove.prevent.stop="move()"
@touchmove.prevent.stop="move()"
@mouseup="end()"
@touchend="end()"
>
<img class="img-kf" src="../../assets/images/csVip/kf.png" />
</div>
2、在data里面设置
position: { x: 0, y: 0 },
nx: "",
ny: "",
dx: "",
dy: "",
xPum: "",
yPum: "",
3、在方法里面写拖拽方法
// 移动端拖拽事件
down() {
this.flags = true;
let touch;
if (event.touches) {
touch = event.touches[0];
} else {
touch = event;
}
this.position.x = touch.clientX;
this.position.y = touch.clientY;
this.dx = moveDiv.offsetLeft;
this.dy = moveDiv.offsetTop;
},
move() {
if (this.flags) {
let touch;
if (event.touches) {
touch = event.touches[0];
} else {
touch = event;
}
this.nx = touch.clientX - this.position.x;
this.ny = touch.clientY - this.position.y;
this.xPum = this.dx + this.nx;
this.yPum = this.dy + this.ny;
//添加限制:只允许在屏幕内拖动
//屏幕宽度减去悬浮框宽高
const maxWidth = document.body.clientWidth - 54;
const maxHeight = document.body.clientHeight - 54;
if (this.xPum < 0) {
//屏幕x限制
this.xPum = 0;
} else if (this.xPum > maxWidth) {
this.xPum = maxWidth;
}
if (this.yPum < 0) {
//屏幕y限制
this.yPum = 0;
} else if (this.yPum > maxHeight) {
this.yPum = maxHeight;
}
moveDiv.style.left = this.xPum + "px";
moveDiv.style.top = this.yPum + "px";
//阻止页面的滑动默认事件
document.addEventListener(
"touchmove",
function () {
// 1.2 如果碰到滑动问题,请注意是否获取到 touchmove
// event.preventDefault(); //jq 阻止冒泡事件
event.stopPropagation(); // 如果没有引入jq 就用 stopPropagation()
},
false
);
}
},
//鼠标释放时候的函数
end() {
this.flags = false;
},
4、css样式
.xuanfu {
width: 1.7rem;
height: 1.7rem;
border-radius: 50%;
// background: rgb(213, 91, 91);
position: fixed;
bottom: 4rem;
right: 0.4rem;
z-index: 9999999999;
text-align: center;
.img-kf {
width: 1.7rem;
height: 1.7rem;
}
}
到这里,我们的悬浮小图标就做完了!!!!