(1)、需求:
- 点击弹出层,会弹出模态框,并且显示灰色半透明的遮挡层
- 点击关闭按钮,可以关闭模态框,并且同时关闭半透明遮挡层
- 鼠标放在模态框最上面一行,可以按住鼠标拖拽模态框在页面中移动
- 鼠标松开,可以停止拖动模态框移动 。
(2)思路:
- 点击弹出层,模态框和遮挡层就会显示出来 display:block
- 点击关闭按钮,模态框和遮罩层会隐藏起来 display:none
- 在页面中拖拽的原理:鼠标按下并且移动,之后松开鼠标
- 触发事件是鼠标按下mousedown,鼠标移动mousemove 鼠标松开 mouseup
- 拖拽过程,鼠标移动过程中,获得最新的值赋值给模态框的left和top值,这样模态框就可以跟着鼠标走了
- 鼠标按下触发的事件源是h2
- 鼠标的坐标减去鼠标内的坐标,才是模态框真正的位置
- 鼠标按下,我们要得到鼠标在盒子的坐标
- 鼠标移动,就让模态框的坐标设置为:鼠标坐标减去盒子坐标即可,注意移动时间写到按下
- 鼠标松开,就停止拖拽,可以让鼠标移动事件解除
(3)、es6代码
<script>
let that;
class Modal {
constructor() {
that = this;
// 获取元素
this.clickH1 = document.getElementById("clickH1");
this.btn = document.getElementById("btn");
this.modalBox = document.querySelector(".modal-box");
this.bg = document.querySelector(".bg");
this.title = document.querySelector(".title");
// 调用监听函数
this.event();
}
// 监听函数
event() {
this.clickH1.addEventListener("click", this.clickH1Fun);
this.btn.addEventListener("click", this.btnFun);
this.title.addEventListener("mousedown", this.titleFun);
}
// 点击出现遮罩层
clickH1Fun() {
that.bg.style.display = "block";
that.modalBox.style.display = "block";
}
// 点击关闭按钮
btnFun() {
that.bg.style.display = "none";
that.modalBox.style.display = "none";
}
//鼠标按下title
titleFun(e) {
// 获取鼠标在模态框中的位置方式一
let x = e.offsetX;
let y = e.offsetY;
// 获取鼠标在模态框中的位置方式二
// let x = e.pageX - that.modalBox.offsetLeft;
// let y = e.pageY - that.modalBox.offsetTop;
console.log(x, y);
document.addEventListener("mousemove", moveFun);
function moveFun(e) {
// console.log(111);
let left = e.pageX - x;
let right = e.pageY - y;
that.modalBox.style.left = left + "px";
that.modalBox.style.top = right + "px";
that.modalBox.style.margin = 0; //left 值变化,由于过度约束,需要重新设置margin
// that.modalBox.style.transform='translate(0%, 0%)'//left 值变化,由于过度约束,需要重新设置偏移量
}
document.addEventListener("mouseup", upFun);
function upFun() {
document.removeEventListener("mousemove", moveFun);
}
}
}
new Modal();
</script>