第 132 题:实现一个 Dialog 类,Dialog可以创建 dialog 对话框,对话框支持可拖拽
class Dialog {
constructor(text) {
this.lastX = 0
this.lastY = 0
this.x
this.y
this.text = text || ''
this.isMoving = false
this.dialog
}
open() {
const model = document.createElement('div')
model.id='model'
model.style = `
position:absolute;
top:0;
left:0;
bottom:0;
right:0;
background-color:rgba(0,0,0,.3);
display:flex;
justify-content: center;
align-items: center;`
model.addEventListener('click',this.close.bind(this))
document.body.appendChild(model)
this.dialog = document.createElement('div')
this.dialog.style = `
padding:20px;
background-color:white`
this.dialog.innerText = this.text
this.dialog.addEventListener('click',e=>{e.stopPropagation()})
this.dialog.addEventListener('mousedown', this.handleMousedown.bind(this))
document.addEventListener('mousemove', this.handleMousemove.bind(this))
document.addEventListener('mouseup', this.handleMouseup.bind(this))
model.appendChild(this.dialog)
}
close() {
this.dialog.removeEventListener('mousedown',this.handleMousedown)
document.removeEventListener('mousemove', this.handleMousemove)
document.removeEventListener('mouseup',this.handleMouseup)
document.body.removeChild(document.querySelector('#model'))
}
handleMousedown(e) {
this.isMoving = true
this.x = e.clientX
this.y = e.clientY
}
handleMousemove(e) {
if (this.isMoving) {
this.dialog.style.transform = `translate(${e.clientX - this.x + this.lastX}px,${e.clientY - this.y + this.lastY}px)`
}
}
handleMouseup(e) {
this.lastX = e.clientX - this.x + this.lastX
this.lastY = e.clientY - this.y + this.lastY
this.isMoving = false
}
}
let dialog = new Dialog('Hello')
dialog.open()
只是实现了拖动,记录一下 class Dialog{ constructor(){ this.dialog, this.startX,this.startY, this.currentX,this.currentY, this.isMoveing = false } open(){
this.dialog = document.createElement("div");
this.dialog.style = `
width:200px;
height:200px;
background:rgba(0.0.0.,5);
position:absolute;
left:0;
top:0;`;
document.body.appendChild(this.dialog);
this.dialog.addEventListener('mousedown',this.mousedown.bind(this));
document.addEventListener('mousemove',this.mousemove.bind(this));
document.addEventListener('mouseup',this.mouseup.bind(this));
}
mousedown(event){
this.isMoveing = true;
this.startX = event.clientX - this.dialog.offsetLeft;
this.startY = event.clientY - this.dialog.offsetTop;
}
mousemove(event){
if(!this.isMoveing){
return;
}
this.currentX = event.clientX;
this.currentY = event.clientY;
var left = this.currentX - this.startX;
var top = this.currentY - this.startY;
var bodyWidth = document.documentElement.clientWidth || document.body.clientWidth;
var bodyHeight = document.documentElement.clientHeight || document.body.cliengHeight;
if(left <= 0){
left = 0;
}else if(left >= bodyWidth - this.dialog.offsetWidth){
left = bodyWidth - this.dialog.offsetWidth;
}
if(top <= 0){
top = 0;
}else if(top >= bodyHeight - this.dialog.offsetHeight){
top = bodyHeight - this.dialog.offsetHeight
}
this.dialog.style.left = left + 'px';
this.dialog.style.top = top + 'px';
}
mouseup(event){
this.isMoveing = false;
document.removeEventListener('mousemove', this.mousemove);
document.removeEventListener('mouseup',this.mouseup);
}
}
var dialog = new Dialog();
dialog.open();
drag、dragstart,dragend
class Dialog {
constructor({title,content}){
this.title = title;
this.content = content;
this._dialog = null; // 全局保存DOM
this.dialogCss = { // 样式
position:"absolute",
left:"50%",
top:"50%",
width:"400px",
height:"240px",
border:"1px solid #aaa",
"box-shadow":"0 2px 3px #aaa",
"border-radius":"5px",
transform:"translate(-50%,-50%)",
cursor:"pointer"
}
this.dialogTitleCss = {
'border-bottom':'1px solid #aaa',
'margin-bottom':'10px',
"padding":"10px",
"margin-top":0,
}
this.dialogContentCss = {
}
}
init(){ // 创建窗口
let dialog = document.createElement("div");
let title = document.createElement("h3");
let content = document.createElement("div");
title.innerText = this.title;
let close = document.createElement("i");
close.style["float"] = "right";
close.innerText = "X";
title.appendChild(close);
dialog.appendChild(title);
content.innerHTML = this.content;
dialog.appendChild(content);
dialog.id = "dialog_custom";
dialog.setAttribute("draggable",true);
for(let key in this.dialogCss){
dialog.style[key] = this.dialogCss[key]
}
for(let key in this.dialogTitleCss){
title.style[key] = this.dialogTitleCss[key]
}
document.body.appendChild(dialog) ;
this._dialog = dialog;
close.addEventListener("click",this.close.bind(this));
dialog.addEventListener("drag",this.beforeDrag); // 监听拖动事件
dialog.addEventListener("dragstart",this.onDrag.bind(this));
dialog.addEventListener("dragend",this.afterDrag.bind(this));
}
close(){
this._dialog.remove(); // 窗口手动关闭
}
beforeDrag(){
// console.log("拖动了");
}
onDrag(event){
this._dialog.style.opacity = 0.5;
}
afterDrag(event){
// console.log(event);
this._dialog.style.opacity = 1;
this._dialog.style.transform = "";
this._dialog.style.left = event.x+"px";
this._dialog.style.top = event.y+"px";
}
}
new Dialog({
title:"弹窗",
content:"这是一个弹窗",
}).init();
楼上的都很优秀,再加上一些回调就更完美了。
代码
通过 webpack 打包成一个 npm 包,项目地址:https://github.com/SimpleCodeCX/simple-dialog
demo
Install
npm install --save @simplexd/dialog
Usage
// commonjs
const Dialog = require('@simplexd/dialog');
const dialog = new Dialog();
dialog.open();
or
// es6 module
import Dialog from '@simplexd/dialog';
const dialog = new Dialog();
dialog.open();
or
// html script
<link rel="stylesheet" href="${your-asset-src-path}/simple-dialog.min.css">
<script src="${your-asset-src-path}/simple-dialog.min.js"></script>
const dialog = new SimpleDialog();
dialog.open();
Example
const dialog1 = new Dialog();
dialog1.open();
dialog1.close();
const dialog2 = new Dialog({
title: 'dialog2 title',
text: 'this is dialog2'
});
dialog2.open();
dialog2.close();
const dialog3 = new Dialog({
title: 'normal dialog3',
text: 'this is dialog3',
size: 'normal' || 'small' || 'large'
});
dialog3.open();
dialog3.close();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.dialog{
position: absolute;
border: 1px solid black;
padding: 5px 30px;
text-align: center;
cursor: pointer;
user-select: none;
}
</style>
</head>
<body>
<script>
class Dialog{
constructor(title, content, left = 0, top = 0){
this.title = title;
this.content = content;
this.left = left;
this.top = top;
}
createDom(){
this.dom = document.createElement("div");
let oH1 = document.createElement("h1");
oH1.innerHTML = this.title;
let oP = document.createElement("p");
oP.innerHTML = this.content;
this.dom.appendChild(oH1);
this.dom.appendChild(oP);
this.dom.style.left = this.left + "px";
this.dom.style.top = this.top + "px";
this.dom.className = 'dialog';
document.body.appendChild(this.dom);
this.addEvent();
return this;
}
addEvent(){
this.dom.onmousedown = function(e){
let startX = e.clientX;
let startY = e.clientY;
let left = this.offsetLeft;
let top = this.offsetTop;
document.onmousemove = (e) => {
let moveX = e.clientX;
let moveY = e.clientY;
this.style.left = left + (moveX - startX) + "px";
this.style.top = top + (moveY - startY) + "px";
};
document.onmouseup = (e) => {
document.onmousemove = document.onmouseup = null;
};
};
return this;
}
}
class autoCloseDialog extends Dialog{
constructor(title, content, left = 0, top = 0, timer = 5000){
super(title, content, left, top);
this.timer = timer;
}
addEvent(){
window.setTimeout(() => {
document.body.removeChild(this.dom);
}, this.timer);
super.addEvent();
}
}
new Dialog("你好啊", "测试", 100, 200).createDom();
new Dialog("你好啊2", "测试2").createDom();
new autoCloseDialog("你好啊3", "测试3,3s后自动关闭", 500, 0, 3000).createDom();
</script>
</body>
</html>
实现的方法很多,都可以随意扩展,随便写写。需要注意的地方:
- 使用事件代理挂在document下,这样子防止拖得快的时候滑手
- 如果需要动画打开关闭,则不可以马上删除元素了,应该要切换样式来实现或者延迟一阵删元素。antd的modal是默认切样式,加上destroyonclose会等动画播完再删元素
- 使用的时候不要反复new,一个实例应该要做到无数次复用
展开查看全部代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>dialog</title>
<style>
body {
height: 100vh;
}
.dlg-warpper {
background-color: rgba(0, 0, 0, .8);
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 1;
}
.x-dialog {
position: absolute;
z-index: 2;
background-color: #fff;
left: 50%;
top: 50%;
width: 200px;
text-align: center;
border-radius: 8px;
border: 1px solid #000;
padding: 16px;
user-select: none;
}
.x-dialog header {
font-weight: bolder;
}
.x-dialog footer {
display: flex;
justify-content: space-around;
}
</style>
</head>
<body></body>
<script>
class Dialog {
constructor(opts = {}) {
this.onCancel = opts.onCancel || (() => {});
this.onOk = opts.onOk || (() => {});
this.title = opts.title || "please enter title";
this.body = opts.body || "please enter body";
this.footer = opts.footer || [
{
title: "cancel"
},
{
title: "ok"
}
];
this.warpper();
this.init();
this.drag();
this.warp.appendChild(this.dom)
}
init() {
const dom = document.createElement("aside");
dom.className = "x-dialog";
dom.innerHTML = `
<header>${this.title}</header>
<section>${this.body}</section>
`;
this.dom = dom;
Object.defineProperty(this, "_dom", {
get() {
return this.dom;
},
set(val) {
val
? val.appendChild(this.warp)
: this.warp.parentNode &&
this.warp.parentNode.removeChild(this.warp);
}
});
this.renderFooter();
}
open(mountNode = document.body) {
this._dom = mountNode;
}
close() {
this._dom = null;
}
warpper() {
const warp = document.createElement('div');
warp.className = 'dlg-warpper'
this.warp = warp;
}
renderFooter() {
if (this.footer) {
const footer = document.createElement("footer");
const btns = this.footer.map(({ title = "unknown" }, index) => {
const btn = document.createElement("button");
btn.dataset.midIndex = index;
btn.innerText = title;
footer.appendChild(btn);
return btn;
});
footer.addEventListener("click", e => {
const currentIndex = e.target.dataset.midIndex;
(this.footer[currentIndex].cb || (() => {})).call(btns[currentIndex],e);
this.close();
});
this.dom.appendChild(footer);
}
}
drag() {
let diffX = 0;
let diffY = 0;
const handleDrag = e => {
const { x, y } = this.dom.getBoundingClientRect();
this.dom.style.left = x + e.clientX - diffX + "px";
this.dom.style.top = y + e.clientY - diffY + "px";
diffX = e.clientX;
diffY = e.clientY;
};
document.addEventListener("mousedown", e => {
if (e.path.includes(this.dom)) {
const { x, y } = this.dom.getBoundingClientRect();
diffX = e.clientX;
diffY = e.clientY;
document.addEventListener("mousemove", handleDrag);
} else {
e.preventDefault();
}
});
document.addEventListener("mouseup", e => {
diffX = 0;
diffY = 0;
document.removeEventListener("mousemove", handleDrag);
});
}
}
const instance = new Dialog();
instance.open();
</script>
</html>

`class Dialog { constructor({ width, height, title }) { this.width = width || 400; this.height = height || 500; this.title = title || 'test'; this.$dialog = null; this._openDialog(); }
_getDialog() {
const $dialog = document.getElementById('fePrivateDialog');
return $dialog;
}
_openDialog() {
let $dialog = this._getDialog();
if (!$dialog) {
$dialog = document.createElement('div');
$dialog.id = 'fePrivateDialog';
const $title = document.createElement('div');
const $titleContent = document.createElement('p');
$titleContent.innerText = this.title;
$titleContent.style = "margin:0;padding:0;padding-right:30px;text-align:center; position:relative"
const $close = document.createElement('span');
$close.innerText = 'x';
$close.style = "position:absolute;top:50%;right:10px;transform:translateY(-50%);cursor:pointer;padding:0 10px"
$dialog.appendChild($title);
$title.appendChild($titleContent);
$titleContent.appendChild($close);
document.body.appendChild($dialog);
this._initEvent($dialog, $close);
}
this.$dialog = $dialog;
$dialog.style = "position:fixed;display:none;border:1px solid #e5e5e5; border-radius:4px";
$dialog.draggable = true;
$dialog.style.width = this.width + "px";
$dialog.style.height = this.height + "px";
const clientWidth = document.body.clientWidth;
const clientHeight = document.body.clientHeight;
this.top = (clientHeight - this.height) / 2;
this.left = (clientWidth - this.width) / 2;
$dialog.style.top = this.top + "px";
$dialog.style.left = this.left + "px";
}
_initEvent($dialog, $close) {
$dialog.addEventListener('dragend', (event) => {
const { offsetX, offsetY } = event || {};
const diffX = offsetX - this._offsetX;
const diffY = offsetY - this._offsetY;
$dialog.style.top = this.top + diffY + 'px';
$dialog.style.left = this.left + diffX + 'px';
this.top = this.top + diffY;
this.left = this.left + diffX;
});
$dialog.addEventListener('dragstart', (event) => {
const { offsetX, offsetY } = event || {};
this._offsetX = offsetX;
this._offsetY = offsetY;
});
$close.addEventListener('click', () => {
if (this.$dialog) {
this.$dialog.style.display = 'none';
this._initData();
}
})
}
_initData() {
const clientWidth = document.body.clientWidth;
const clientHeight = document.body.clientHeight;
this.top = (clientHeight - this.height) / 2;
this.left = (clientWidth - this.width) / 2;
this.diffX = 0;
this.diffY = 0;
this._offsetX = 0;
this._offsetY = 0;
}
showDialog() {
if (this.$dialog) {
this.$dialog.style.display = 'block';
}
}
}`
@5SSS 犀利
class modal {
constructor() {
this.warpper = document.createElement('div')
this.bodyDom = document.querySelector('body')
this.data = {
x: 200,
y: 300
}
for (let i in this.data) {
this.defineReactive(this.data, i, this.data[i])
}
this.init()
}
render() {
this.warpper.style = `position:fixed;width:200px;height:300px;
top: ${this.data.y}px; left:${this.data.x}px; background: #000`;
let dom = `<div class="modal">
<div class="diaog" style="color:#fff">555</div>
</div>`
this.warpper.innerHTML = dom
this.bodyDom.appendChild(this.warpper)
}
defineReactive(data, key, val) {
Object.defineProperty(data, key, {
enumerable: true, // 可枚举
configurable: false, // 不能再define
get: function () {
return val;
},
set: (newVal) => {
console.log('哈哈哈,监听到值变化了 ', val, ' --> ', newVal);
val = newVal;
this.render()
}
});
}
init() {
this.render()
this.bindDragEvent()
}
bindDragEvent() {
this.warpper.onmousedown = (e) => {
if (e.target.className === 'diaog') {
const {
x,
y
} = this.warpper.getBoundingClientRect();
this.warpperX = x
this.warpperY = y
this.start = true
this.diffX = e.clientX
this.diffY = e.clientY
}
}
window.onmousemove = (e) => {
if (this.start) {
this.data.x = this.warpperX + e.clientX - this.diffX
this.data.y = this.warpperY + e.clientY - this.diffY
}
}
window.onmouseup = (e) => {
this.start = false
this.diffX = 0
this.diffY = 0
}
}
}
new modal()
class Dialog{
constructor(){
this.x = 0;
this.y = 0;
this.moving = false;
this.lastX = 0;
this.lastY = 0;
}
open(){
console.log("ddd")
let div = document.createElement("div");
div.style = `width:100px;height:100px;background:red;position:absolute;
top:0;
left:0;
bottom:0;
right:0;`;
// 添加监听事件
div.id = "dia";
// 鼠标点击下去的事件
div.addEventListener("mousedown",this.mousedown.bind(this))
// 鼠标拖拽事件
div.addEventListener("mousemove",this.mousemove.bind(this))
// 鼠标抬起事件
div.addEventListener("mouseup",this.mouseup.bind(this))
document.body.appendChild(div)
}
mousedown(event){
this.x = event.clientX;
this.y = event.clientY;
console.log("X:"+this.x)
this.moving = true;
}
mousemove(event){
if(this.moving){
console.log(event.target)
event.target.style.transform = `translate(${event.clientX - this.x + this.lastX}px,${event.clientY - this.y + this.lastY}px)`
}
}
mouseup(event){
this.lastX = event.clientX - this.x + this.lastX;
this.lastY = event.clientY - this.y + this.lastY;
this.moving = false;
console.log(this.moving)
}
}
let dia = new Dialog();
dia.open();
class Dialog { constructor(text) { this.lastX = 0 this.lastY = 0 this.x this.y this.text = text || '' this.isMoving = false this.dialog } open() { const model = document.createElement('div') model.id='model' model.style = ` position:absolute; top:0; left:0; bottom:0; right:0; background-color:rgba(0,0,0,.3); display:flex; justify-content: center; align-items: center;` model.addEventListener('click',this.close.bind(this)) document.body.appendChild(model) this.dialog = document.createElement('div') this.dialog.style = ` padding:20px; background-color:white` this.dialog.innerText = this.text this.dialog.addEventListener('click',e=>{e.stopPropagation()}) this.dialog.addEventListener('mousedown', this.handleMousedown.bind(this)) document.addEventListener('mousemove', this.handleMousemove.bind(this)) document.addEventListener('mouseup', this.handleMouseup.bind(this)) model.appendChild(this.dialog) } close() { this.dialog.removeEventListener('mousedown',this.handleMousedown) document.removeEventListener('mousemove', this.handleMousemove) document.removeEventListener('mouseup',this.handleMouseup) document.body.removeChild(document.querySelector('#model')) } handleMousedown(e) { this.isMoving = true this.x = e.clientX this.y = e.clientY } handleMousemove(e) { if (this.isMoving) { this.dialog.style.transform = `translate(${e.clientX - this.x + this.lastX}px,${e.clientY - this.y + this.lastY}px)` } } handleMouseup(e) { this.lastX = e.clientX - this.x + this.lastX this.lastY = e.clientY - this.y + this.lastY this.isMoving = false } } let dialog = new Dialog('Hello') dialog.open()
handleMouseup应该绑定在div上。不然在没关闭的情况下,第二次拖拽会有偏移量。
class Dialog { constructor(text) { this.lastX = 0 this.lastY = 0 this.x this.y this.text = text || '' this.isMoving = false this.dialog } open() { const model = document.createElement('div') model.id='model' model.style = ` position:absolute; top:0; left:0; bottom:0; right:0; background-color:rgba(0,0,0,.3); display:flex; justify-content: center; align-items: center;` model.addEventListener('click',this.close.bind(this)) document.body.appendChild(model) this.dialog = document.createElement('div') this.dialog.style = ` padding:20px; background-color:white` this.dialog.innerText = this.text this.dialog.addEventListener('click',e=>{e.stopPropagation()}) this.dialog.addEventListener('mousedown', this.handleMousedown.bind(this)) document.addEventListener('mousemove', this.handleMousemove.bind(this)) document.addEventListener('mouseup', this.handleMouseup.bind(this)) model.appendChild(this.dialog) } close() { this.dialog.removeEventListener('mousedown',this.handleMousedown) document.removeEventListener('mousemove', this.handleMousemove) document.removeEventListener('mouseup',this.handleMouseup) document.body.removeChild(document.querySelector('#model')) } handleMousedown(e) { this.isMoving = true this.x = e.clientX this.y = e.clientY } handleMousemove(e) { if (this.isMoving) { this.dialog.style.transform = `translate(${e.clientX - this.x + this.lastX}px,${e.clientY - this.y + this.lastY}px)` } } handleMouseup(e) { this.lastX = e.clientX - this.x + this.lastX this.lastY = e.clientY - this.y + this.lastY this.isMoving = false } } let dialog = new Dialog('Hello') dialog.open()handleMouseup应该绑定在div上。不然在没关闭的情况下,第二次拖拽会有偏移量。
绑在全局的好处是:如果快速拖拽,元素跟随鼠标轨迹的时候如果没有跟上,之后可以再同步
@MBearo 在close的时候,是无法删掉之前绑定的事件的,因为之前添加事件的时候bind方法会返回一个新的方法,而不是dialog中包含的方法。
写了一个满足基本要求的简易版的 让不明白的同学能够更快看懂
class Dialog {
constructor(top,left,width,height) {
this.top = top
this.left = left
this.el = null
this.w = width
this.h = height
this.originX = 0
this.originY = 0
this.mouseL = 0
this.mouseT = 0
}
show(content) {
this.el = document.createElement('div')
document.body.appendChild(this.el)
this.el.style = `
width:${this.w}px;
height:${this.h}px;
position:absolute;
top:${this.top}px;
left:${this.left}px;
border:1px solid #ccc;
`
this.el.innerHTML = content
this.el.addEventListener('mousedown',function(e) {
this.originX = e.pageX
this.originY = e.pageY
this.mouseL = this.originX - this.offsetLeft
this.mouseT = this.originY - this.offsetTop
function move(e) {
this.style.left = (e.pageX - this.mouseL) + 'px'
this.style.top = (e.pageY - this.mouseT) + 'px'
}
this.addEventListener('mousemove',move)
this.addEventListener('mouseup',function(e) {
this.removeEventListener('mousemove',move)
})
})
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<script src="./dialog类.js"></script>
<script>
new Dialog(100,100,500,500).show('helloworld')
</script>
</body>
</html>
class Dialog {
constructor() {
this.instance = null
this._id = 0
this.lastX = this.lastY = 0
}
getOption(option) {
const _default = {
tag: 'div',
class: 'class-name'
}
return _.merge(_default, option)
}
create(option = {}) {
const options = this.getOption(option)
this.instance = document.createElement(options.tag)
this.instance.setAttribute('data-dialog-id', this._id++)
this.instance.classList.add(options.class)
document.body.appendChild(this.instance)
}
drag(handle) {
const { move, start, end } = handle
this.instance.addEventListener('mousedown', e => {
if (this.isMouseLeft(e.buttons)) {
this.x = e.clientX
this.y = e.clientY
if (typeof start === 'function') {
start.call(this, e)
}
}
})
this.instance.addEventListener('mouseup', e => {
this.lastX = e.clientX - this.x + this.lastX
this.lastY = e.clientY - this.y + this.lastY
if (typeof start === 'function') {
end.call(this, e)
}
})
this.instance.addEventListener('mousemove', e => {
if (this.isMouseLeft(e.buttons)) {
const { clientX, clientY } = e
setTimeout(() => {
this.set(`translate(${clientX - this.x + this.lastX}px,${clientY - this.y + this.lastY}px)`)
}, 0)
if (typeof start === 'function') {
move.call(this, e)
}
}
})
}
isMouseLeft(buttons) {
return buttons === 1
}
set(style) {
this.instance.style.transform = style
}
}
const dialog = new Dialog()
dialog.create()
dialog.drag({
move: e => {
console.log(e.type)
},
end: e => {
console.log(e.type)
},
start: e => {
console.log(e.type)
}
})