创建一个DragIcon.js用于逻辑代码编写
/**
* 可拖拽悬浮框
*
* el:被拖拽的元素,如:#dragIcon|.dragIcon
*
* top:初始化悬浮框距离窗口顶部的距离,如100px|10%
*
* left:初始化悬浮框距离窗口左边的距离,如100px|10%
*
* onClick:悬浮框点击触发事件
**/
class DragIcon {
static DEFINED_CONFIG = {
el: '#dragIcon',
top: '100px',
left: '100px',
onClick: () => {
}
}
constructor(options) {
if (Object.prototype.toString.call(options) !== '[object Object]') {
throw "配置项必须为对象,你传递的是" + Object.prototype.toString.call(options);
}
this.config = Object.assign({}, DragIcon.DEFINED_CONFIG, options);
this.dragElement = document.querySelector(this.config.el);
this.clientWidth = document.documentElement.clientWidth || window.innerWidth;
this.clientHeight = document.documentElement.clientHeight || window.innerHeight;
this.create();
this.drag();
this.isDragging = false; // 初始化时未拖拽
}
/**
* 初始化悬浮框
**/
create() {
const {
top,
left
} = this.config;
this.dragElement.style.top = `${top}`;
this.dragElement.style.left = `${left}`;
}
/**
* 悬浮框拖拽事件
**/
drag() {
this.dragElement.addEventListener("mousedown", (e) => {
e.preventDefault();
this.isDragging = true; // 拖拽开始
const rect = this.dragElement.getBoundingClientRect();
const disX = e.clientX - rect.left;
const disY = e.clientY - rect.top;
const onMouseMove = (e) => {
let moveX = e.clientX - disX;
let moveY = e.clientY - disY;
moveX = Math.min(moveX, this.clientWidth - rect.width);
moveY = Math.min(moveY, this.clientHeight - rect.height);
moveX = Math.max(0, moveX);
moveY = Math.max(0, moveY)
this.dragElement.style.left = `${moveX}px`;
this.dragElement.style.top = `${moveY}px`;
this.isDragging = false; // 拖拽结束
}
const onMouseUp = () => {
window.removeEventListener("mousemove", onMouseMove);
window.removeEventListener("mouseup", onMouseUp);
this.onClick();
}
window.addEventListener("mousemove", onMouseMove);
window.addEventListener("mouseup", onMouseUp);
});
}
/**
* 悬浮框点击事件
**/
onClick() {
if (this.isDragging) {
this.config.onClick();
this.isDragging = false; // 拖拽结束
}
}
}
使用示例代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
* {
padding: 0px;
margin: 0px;
box-sizing: border-box;
}
#dragIcon {
border: 1px solid #00a2ef;
border-radius: 8px;
width: 100px;
height: 100px;
position: fixed;
cursor: pointer;
z-index: 999;
}
#icon {
border: 1px solid red;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div id="dragIcon">
<div id="icon"></div>
</div>
</body>
<script src="js/DragIcon.js"></script>
<script type="text/javascript">
new DragIcon({
el: '#dragIcon',
top: '100px',
left: '100px',
onClick: () => {
console.log("我是点击事件")
}
});
</script>
</html>
添加了npm i miao-drag下载依赖包
npm i miao-drag
在vue中使用案例
<script setup>
import {
onMounted
} from 'vue'
import dragIcon from "miao-drag"
onMounted(() => {
new dragIcon({
el: '#dragIcon',
top: '100px',
left: '100px',
onClick: () => {
console.log("我是点击事件789")
}
});
});
</script>