项目遇到的,记录一下。
项目场景:
1、一个弹窗,默认居中,不能有遮罩层。
2、这个弹窗大小不固定。
3、可以拖动,但不能超出。
HTML:
<div class="moveEle"></div>
CSS:
* {
margin: 0;
padding: 0;
}
.moveEle {
width: 600px;
height: 400px;
background: black;
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
JS:
// 是否可以移动
let drag = false;
// 初始值
let init = {
// 鼠标的初始位置
x: null,
y: null,
// 和css中的保持一致
top: 50,
left: 50,
};
// 获取标签
const ele = document.querySelector('.moveEle')
// 记录元素最后的位置
function recordLastPos() {
const ele = document.querySelector('.moveEle')
init.left = ele.style.left.substring(0, ele.style.left.length - 1) * 1
init.top = ele.style.top.substring(0, ele.style.top.length - 1) * 1
}
// 鼠标按下
ele.addEventListener("mousedown", e => {
drag = true
// 记录下鼠标的初始位置
init.x = e.clientX
init.y = e.clientY
})
// 鼠标抬起
ele.addEventListener("mouseup", e => {
drag = false
recordLastPos()
})
// 鼠标离开元素
ele.addEventListener("mouseleave", e => {
drag = false
recordLastPos()
})
// 鼠标移动
ele.addEventListener("mousemove", e => {
// 当鼠标按下
if (drag) {
// 获取标签
const moveEle = document.querySelector('.moveEle')
// 获取当前页面的可视区域宽高
const windowWidth = window.innerWidth
const windowHeight = window.innerHeight
// 鼠标当前移动的位置
const curX = e.clientX
const curY = e.clientY
// 鼠标初始位置
const initX = init.x
const initY = init.y
// 位置初始值(百分比)
let left = init.left
let top = init.top
// 计算移动的百分比
let leftPer = ((curX - initX) / windowWidth) * 100
let topPer = ((curY - initY) / windowHeight) * 100
// 计算差值比例
let leftDiff = windowWidth / (windowWidth - moveEle.clientWidth)
let topDiff = windowHeight / (windowHeight - moveEle.clientHeight)
// 计算最终所在位置的百分比
let moveLeftPer = left + leftPer * leftDiff
let moveTopPer = top + topPer * topDiff
// 设定不超出边界
if (moveLeftPer >= 100) {
moveLeftPer = 100
} else if (moveLeftPer <= 0) {
moveLeftPer = 0
}
if (moveTopPer >= 100) {
moveTopPer = 100
} else if (moveTopPer <= 0) {
moveTopPer = 0
}
// 更改位置
moveEle.style.left = moveLeftPer + '%'
moveEle.style.top = moveTopPer + '%'
moveEle.style.transform = `translate(-${moveLeftPer}%, -${moveTopPer}%)`
}
})