css
把模态框用固定定位,top和left设为50%;
然后用tranform:translate(-50%,-50%)来水平居中,垂直居中
思路
- 获取元素
- 点击弹出层这个链接link 让mask和login显示出来
- 点击closeBtn就隐藏mask和login
- 再也页面拖拽的原理,鼠标按下并且移动,之后松开鼠标
- 触发事件是鼠标按下mousedown,鼠标移动mousemove鼠标松开mouseup(原理其实就是事件追随鼠标:获取鼠标的值让后把这个值赋给模态框)
- 侦听源:鼠标按下触发的事件我选择事件的上方,另外加一个id未title
- 鼠标的坐标减去鼠标在盒子内的坐标,才是模态框真正的位置
- 鼠标按下:获得鼠标在盒子里的坐标
- 鼠标移动:就让模态框的坐标设置为鼠标在页面中的坐标减去鼠标在盒子内的坐标即可,移动事件写道按下事件里面
- 鼠标松开:就停止拖拽,就是可以让鼠标移动事件解除
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
body,html {
height: 100%;
width: 100%;
}
.mask {
opacity: 0.6;
z-index: -11;
filter: Alpha;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
background-color: none;
}
.box {
width: 30%;
height: 30%;
background-color: black;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
display: none;
cursor: move;
}
.title {
width: 100%;
height: 50%;
background-color: red;
}
</style>
<body>
<div class="mask">
<div class="box">
<div class="title">
</div>
<button id=closebtn>关闭</button>
</div>
<div class="link">点击登录</div>
</div>
<script>
var mask = document.querySelector(".mask");
var closebtn = document.querySelector("#closebtn");
var box = document.querySelector(".box");
var link = document.querySelector(".link");
var title = document.querySelector(".title");
link.addEventListener('click',function(e){
mask.style.background = "rgba(1,1,1,.2)";
box.style.display = "block";
})
closebtn.addEventListener('click',function(e){
mask.style.background = "none";
box.style.display = "none";
})
//开始拖拽
//1.鼠标按下的时候,获得鼠标在盒子内的坐标
title.addEventListener('mousedown',function(e){
var x = e.pageX - box.offsetLeft;
var y = e.pageY - box.offsetTop;
//2.鼠标移动的时候,把鼠标在页面中的坐标 减去 鼠标在盒子中的坐标,得到盒子的left和top
document.addEventListener('mousemove',move)
function move(e) {
box.style.left = e.pageX - x +'px';
box.style.top = e.pageY - y + 'px';
}
//3.鼠标弹起,就让鼠标移动事件移除
document.addEventListener('mouseup',function(){
document.removeEventListener('mousemove',move);
})
})
</script>
</body>
</html>