<!DOCTYPE html>
<html lang="zh-CN">
<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>模态框拖拽</title>
<style>
body {
position: relative;
}
div {
position: absolute;
left: 0;
top: 0;
width: 200px;
height: 200px;
background-color: pink;
}
</style>
</head>
<body>
<div>
<h1>点此拖拽</h1>
</div>
<script>
h1 = document.querySelector('h1')
div = document.querySelector('div')
h1.addEventListener('mousedown', (e) => {
let x = e.pageX - div.offsetLeft
let y = e.pageY - div.offsetTop
function move(e) {
div_x = e.pageX - x + 'px'
div_y = e.pageY - y + 'px'
div.style.left = div_x
div.style.top = div_y
}
document.addEventListener('mousemove', move)
h1.addEventListener('mouseup', () => {
document.removeEventListener('mousemove', move)
})
})
</script>
</body>
</html>
JS实现模态框拖拽
最新推荐文章于 2024-05-14 16:42:53 发布