Web开发:一个可拖拽的模态框(HTML、CSS、JavaScript)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Draggable Modal</title>
<style>
.modal {
width: 300px;
position: absolute;
top: 50px;
left: 50px;
border: 1px solid #000;
padding: 10px;
z-index: 10;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}
.modal-header {
cursor: move;
background-color: #2196F3;
color: white;
padding: 10px;
margin: -10px -10px 10px -10px;
}
.modal-content {
padding: 20px;
}
</style>
</head>
<body>
<div class="modal" id="modal">
<div class="modal-header" id="modal-header">
Drag Me!
</div>
<div class="modal-content">
<p>This is a draggable modal window.</p>
</div>
</div>
<script>
const dragModal = (modal, header) => {
header.onmousedown = dragStart;
let dragging = false;
let mouseX, mouseY, deltaX, deltaY;
const dragStart = (e) => {
dragging = true;
mouseX = e.clientX;
mouseY = e.clientY;
};
document.onmouseup = () => {
dragging = false;
};
document.onmousemove = (e) => {
if (dragging) {
deltaX = e.clientX - mouseX;
deltaY = e.clientY - mouseY;
mouseX = e.clientX;
mouseY = e.clientY;
modal.style.left = (modal.offsetLeft + deltaX) + 'px';
modal.style.top = (modal.offsetTop + deltaY) + 'px';
}
};
};
const modal = document.getElementById('modal');
const header = document.getElementById('modal-header');
dragModal(modal, header);
</script>
</body>
</html>
这段代码实现了一个可拖拽的模态框。用户可以点击模态框的标题栏并拖动它来移动整个模态框。代码中的dragModal
函数负责处理拖拽逻辑,它设置了必要的事件监听器来响应鼠标的移动和释放事件。
评论已关闭