<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.app {
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
}
.son {
width: 500px;
height: 50px;
position: relative;
top: 10%;
background-color: yellow;
margin: 0 auto;
}
* {
margin: 0;
;
padding: 0;
}
html,body {
height: 100%;
width: 100%;
min-width: 640px;
min-height: 480px;
}
</style>
<body>
<div class="app">
<div class="son">我是弹窗</div>
</div>
<script>
var son = document.querySelector(".son")
son.onmousedown = function (e) {
//获取点击弹窗时的坐标
var disX = e.clientX;
var disY = e.clientY;
// 获取原有属性 ie dom元素.currentStyle 火狐谷歌 window.getComputedStyle(dom元素, null);
const sty = son.currentStyle || window.getComputedStyle(son, null)
let styL, styT, styW;
let maxL, minL, maxT;
// 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
if (sty.left.includes('%')) {
styL = document.documentElement.clientWidth * (parseInt(sty.left.replace(/\%/g, '')) / 100);
} else {
styL = parseInt(sty.left.replace(/\px/g, ''));
}
if (sty.top.includes('%')) {
styT = document.documentElement.clientWidth * (parseInt(sty.top.replace(/\%/g, '')) / 100);
} else {
styT = parseInt(sty.top.replace(/\px/g, ''));
}
//设置弹窗移动最大范围
maxL = (document.documentElement.clientWidth - son.clientWidth) / 2//最大横向
minL = 0 - maxL//最小横向
maxT = document.documentElement.clientHeight - son.clientHeight //最大纵向
document.onmousemove = function (e) {
//计算移动的距离
let l = e.clientX - disX + styL;
let t = e.clientY - disY + styT;
//对弹窗位置进行判断
if (l > maxL) {
l = maxL
}
if (l < minL) {
l = minL
}
if (t > maxT) {
t = maxT
}
if (t < 0) {
t = 0
}
//将位置给left和top
son.style.left = l + "px";
son.style.top = t + 'px'
}
document.onmouseup = function () {
//移除鼠标移动事件
document.onmousemove = null;
};
}
</script>
</body>
</html>
弹窗拖拽,可居中,可限制范围
最新推荐文章于 2024-10-02 05:39:15 发布