首页 > 教程
鼠标拖拽移动DIV
- 2025-04-07
- 1239 ℃
<template>
<div>
<div @mousedown="mousedown">tips</div>
<div>
<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 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>下一篇:一张图片或Div不同位置点击事件
相关内容
怎样在淘宝买东西最便宜
如何使用php与数据库进行交互
可以长按进行倍速播放的...
Vue3 + Vite + Vue ...
网页用JS屏蔽各种按键代码
PHP采集插件QueryList
NodeJs文本相似度去重脚本
微信公众号支付(JSAPI)...
-
推荐39个让你效率提高200%的国外工具软件
2025-03-03 1558
-
黑客万能优盘,自动破解并获取保密数据到U盘
2025-06-16 1680
-
去美国必备口语推荐
2025-03-03 1280
-
Win7和Win10系统隐藏的上帝模式开启方法
2021-10-27 803
-
知网文献免费下载、论文免费查重和去重的方法
2025-03-10 1478
-
微信最快的搜索方法 - 输入#号加内容
2025-06-22 1523
-
拒绝软件捆绑,这些电脑软件下载网站你知道吗
2025-03-10 1892
-
将浏览器窗口变成简单的文本编辑器
2021-10-27 785
-
免费高清素材图片免费下载
2021-11-08 825
-
微信设置电子监护人,杜绝渣男
2025-06-22 1669
文章评论 (0)
- 这篇文章还没有收到评论,赶紧来抢沙发吧~


进入有缘空间
点击分享文章