<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
body {
position: relative;
width: 100vw;
height: 100vh;
}
.box {
position: absolute;
width: 400px;
height: 400px;
background: skyblue;
}
</style>
</head>
<body>
<div class="box" id='box'>
</div>
<script>
const box = document.getElementById('box')
let isDown = false
let mouse = {}
box.onmousedown = (e) => {
isDown = true
box.style.cursor = 'move'
//保存初始位置
mouse = {
startX: e.clientX,
startY: e.clientY,
offsetLeft: box.offsetLeft,
offsetTop: box.offsetTop,
}
}
box.onmousemove = (e) => {
if (!isDown) {
return
}
//计算偏移位置
let offsetLeft = mouse.offsetLeft + e.clientX - mouse.startX
let offsetTop = mouse.offsetTop + e.clientY - mouse.startY
//设置偏移距离的范围[0,window.innerWidth - 400]
offsetLeft = Math.max(0, Math.min(offsetLeft, window.innerWidth - 400))
offsetTop = Math.max(0, Math.min(offsetTop, window.innerHeight - 400))
box.style.left = offsetLeft + 'px';
box.style.top = offsetTop + 'px';
}
//当鼠标滑的太快时,容易移出box,所以在window上监听此事件
window.onmouseup = () => {
isDown = false
box.style.cursor = 'default'
mouse = null
}
</script>
</body>
</html>
Html拖动div窗口
最新推荐文章于 2024-09-08 10:37:23 发布