1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<template>
<div class="vvhan-com">
<div class="title" @mousedown="mousedown">tips</div>
<div class="contain">
<span>这里是内容</span>
</div>
</div>
</template>

<script>
export default {
data() {
return {};
},
methods: {
mousedown(e) {
// 被移动的主体 mainDiv
const mainDiv = document.querySelector(".vvhan-com");
// 鼠标点击位置与主体边的距离
const distanceX = e.clientX - mainDiv.offsetLeft;
const distanceY = e.clientY - mainDiv.offsetTop;
// 鼠标移动事件
document.onmousemove = function (ev) {
const _e = ev || e;
//移动时,鼠标距离当前窗口x轴坐标 - 鼠标在拖拽元素的坐标 = 剩下距离body的x轴坐标
//将这个数值设置为拖拽元素的left、top
let boxLeft = _e.clientX - distanceX;
let boxTop = _e.clientY - distanceY;
//获取body的页面可视宽高
const clientHeight =
document.documentElement.clientHeight || document.body.clientHeight;
const clientWidth =
document.documentElement.clientWidth || document.body.clientWidth;
//限制拖拽宽高
boxLeft =
boxLeft < 0
? 0
: boxLeft > clientWidth - mainDiv.offsetWidth
? clientWidth - mainDiv.offsetWidth
: boxLeft;
boxTop =
boxTop < 0
? 0
: boxTop > clientHeight - mainDiv.offsetHeight
? clientHeight - mainDiv.offsetHeight
: boxTop;

mainDiv.style.top = boxTop + "px";
mainDiv.style.left = boxLeft + "px";
};
// 鼠标松开事件 结束拖拽
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
};
},
},
};
</script>

<style>
body {
position: relative !important;
background: url("https://cache.4ce.cn/ipfs/QmQtvCE2DMkYJKWicdaJxh3Vh47ca6t25RxBGrbre5Cy2p");
background-size: cover;
padding: 0;
margin: 0;
}
</style>

<style lang="scss" scoped>
.vvhan-com {
user-select: none;
position: absolute !important;
box-sizing: border-box;
padding: 6px;
top: 36px;
right: 36px;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
background-color: rgba(255, 255, 255, 0.2);
width: 340px;
z-index: 9;
font-size: 14px;

.title {
margin-bottom: 6px;
font-size: 16px;
line-height: 28px;
border-bottom: 1px rgba(0, 0, 0, 0.1) solid;
cursor: move;
}

h1 {
color: #000;
}
}
</style>