<!DOCTYPE html>
<html lang="zh_CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>可拖拽非模态对话框</title>
<style>
.dialog {
display: none;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background-color: #fff;
border-radius: 8px;
box-shadow: 0 10px 20px rgba(0, 0, 0, .3);
z-index: 9999;
opacity: 0.65;
}
.dialog-header {
background-color: #88c3ff;
padding: 10px;
border-top-left-radius: 8px;
border-top-right-radius: 8px;
cursor: move;
}
.dlgtitle {
font-size: 16px;
color: chartreuse;
}
.dialog-content {
background-color: #c2d6ee;
padding: 20px;
border-bottom-left-radius: 8px;
border-bottom-right-radius: 8px;
}
</style>
</head>
<body>
<button id="openBtn">打开对话框</button>
<div id="dialog" class="dialog close-btn">
<div class="dialog-header">
<span class="dlgtitle">This page say:</span>
</div>
<div class="dialog-content">
<p>请选择一篇博客进行编辑</p>
</div>
</div>
<script>
var dialog = document.getElementById('dialog');
var openBtn = document.getElementById('openBtn');
var bodypage = document.getElementsByTagName('html');
var closeBtn = document.querySelector('.close-btn');
var isDragging = false;
var mouseX, mouseY, dialogLeft, dialogTop;
dialogHeaderMouseDown = function (e) {
isDragging = true;
mouseX = e.clientX;
mouseY = e.clientY;
dialogLeft = dialog.offsetLeft;
dialogTop = dialog.offsetTop;
}
dialogHeaderMouseMove = function (e) {
if (isDragging) {
var moveX = e.clientX - mouseX;
var moveY = e.clientY - mouseY;
dialog.style.left = dialogLeft + moveX + 'px';
dialog.style.top = dialogTop + moveY + 'px';
}
}
dialogHeaderMouseup = function () {
isDragging = false;
}
openBtn.onclick = function () {
dialog.style.display = 'block';
}
closeBtn.onclick = function () {
dialog.style.display = 'none';
}
bodypage[0].onclick = function (e) {
if(e.target!==dialog){
if(e.target!==openBtn){
dialog.style.display = 'none';
}
}
console.log("body is clicked");
}
dialog.onclick = function (e) {
if (e.target == dialog) {
dialog.style.display = 'none';
}
}
var header = document.querySelector('.dialog-header');
header.addEventListener('mousedown', dialogHeaderMouseDown);
header.addEventListener('mousemove', dialogHeaderMouseMove);
header.addEventListener('mouseup', dialogHeaderMouseup);
</script>
</body>
</html>