可以拖动html弹窗源码
html代码:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta name="robots" content="noindex, nofollow" />
<meta name="googlebot" content="noindex, nofollow" />
<title>可拖动弹窗</title>
<script type="text/javascript" src=""></script>
<link rel="stylesheet" type="text/css" href="main.css" />
</head>
<body>
<div class="modal" data-draggable>
<div class="modal-header">可以拖动的弹窗</div>
<div class="modal-content"></div>
</div>
<script type="application/javascript" src="main.js"></script>
</body>
</html>
main.css代码:
html,
body {
padding: 0;
margin: 0;
}
* {
box-sizing: border-box;
}
.modal {
left: 50%;
top: 50%;
position: absolute;
width: 500px;
height: 400px;
background-color: #888;
display: flex;
flex-direction: column;
border: 1px solid #888;
}
.modal-header {
height: 40px;
line-height: 40px;
padding-left: 12px;
user-select: none;
cursor: pointer;
}
.modal-content {
background-color: #fefefe;
flex: 1;
}
main.js代码:
class DraggableWindow {
constructor(el, elDragHandler) {
this.el = el;
this.elDragHandler = elDragHandler;
this.onDragStart = this.onDragStart.bind(this);
this.onDragMove = this.onDragMove.bind(this);
this.onDragEnd = this.onDragEnd.bind(this);
this.startOffsetX = 0;
this.startOffsetY = 0;
this.dragging = false;
this.bindEvents();
}
bindEvents() {
document.body.addEventListener('mousedown', this.onDragStart);
}
onDragStart(evt) {
const { target, offsetX, offsetY, pageX, pageY } = evt;
if (!this.elDragHandler.contains(target)) {
return
}
this.dragging = true;
this.startOffsetX = offsetX;
this.startOffsetY = offsetY;
window.addEventListener('mousemove', this.onDragMove);
window.addEventListener('mouseup', this.onDragEnd);
}
onDragMove(evt) {
const { target, pageX, pageY } = evt;
if (!this.dragging) {
return;
}
this.el.style.left = `${pageX - this.startOffsetX}px`;
this.el.style.top = `${pageY - this.startOffsetY}px`
}
onDragEnd() {
this.dragging = false;
}
}
new DraggableWindow(document.querySelector('.modal'), document.querySelector('.modal-header'))
版权说明
文章采用: 《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权。版权声明:未标注转载均为本站原创,转载时请以链接形式注明文章出处。如有侵权、不妥之处,请联系站长删除。敬请谅解!