<!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>
<style>
*{
margin: 0;
padding: 0;
}
.box{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
width: 300px;
height: 150px;
border: 1px solid #ccc;
}
.header{
width: 100%;
height: 50px;
background-color: pink;
}
.main{
background-color: purple;
}
</style>
</head>
<body>
<div class="box">
<div class="header">头部区域</div>
<div class="main">
内容区域
</div>
</div>
<script>
var header = document.querySelector('.header')
var box = document.querySelector('.box')
// 得到当前鼠标在盒子内的坐标
/**
* 水平方向 = pageX - offsetLeft
* 垂直方向 = pageY - offsetTop
*/
let x = null
let y = null
function moveFn(e){
box.style.left = e.pageX - x + 'px'
box.style.top = e.pageY - y +'px'
}
header.addEventListener('mousedown', function(event) {
// 当鼠标点下的时候
x = event.pageX - box.offsetLeft
y = event.pageY - box.offsetTop
document.addEventListener('mousemove',moveFn)
})
header.addEventListener('mouseup',function(){
document.removeEventListener('mousemove',moveFn)
})
</script>
</body>
</html>
写一个可拖拽的盒子
最新推荐文章于 2023-12-15 11:30:46 发布