直接看代码 有注释
<!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><style>*{margin: 0;padding: 0;}.logins{display: none;width: 512px;height: 200px;position: fixed;left: 50%;top: 50%;background-color: gray;transform: translate(-50%,-50%);box-shadow: 1px 1px 20px #ddd;cursor: move;z-index: 999;}.login-bg{display: none;width: 100%;height: 100%;position: fixed;top: 0px;left: 0px;background: rgba(0,0,0, .2)}.login-input{overflow: hidden;margin: 14px 0px 20px 0px;}.login-input label{float: left; width: 90px;padding-right: 10px; text-align: right;line-height: 35px; height: 35px;font-size: 14px;}.lo-hea{width: 100%;height: 30px;margin: 20px auto;text-align: center;}button{padding-right: 10px;background-color: #fff;margin-left: 100px;}.gb{position: absolute;right: 0;}</style></head>
<body><div class="lo-hea"><a id="link" href="javascript:void();">点击,弹出</a></div><div class="logins" id="title"><div class="gb"> <span class="close"><a href="javascript:void(0);" class="close-login">关闭</a></span></div><div class="login"><div class="login-input"><label for="">用户名</label><input type="text" id="username"></div><div class="login-input"><label for="">密码</label><input type="text" id="psd"></div><button type="submit">登录</button></div></div><!-- 遮盖 --><div class="login-bg"></div><script>var login = document.querySelector('.logins');var msk = document.querySelector('.login-bg');var link = document.getElementById('link');var close = document.querySelector('.close');var title = document.getElementById('title');// 点击展示link.addEventListener('click',function(e){msk.style.display = 'block';login.style.display = 'block';})// 点击关闭隐藏close.addEventListener('click',function(e){msk.style.display = 'none';login.style.display = 'none';})// 拖拽 // 鼠标按下获取盒子坐标title.addEventListener('mousedown',function(e){var x = e.pageX - login.offsetLeft;var y = e.pageY - login.offsetTop;// 鼠标移动 鼠标坐标 减去在盒子内的坐标就是 模态框的 left topdocument.addEventListener('mousemove',moeve)function moeve (e){login.style.left = e.pageX - x + 'px';login.style.top = e.pageY - y + 'px';}// 鼠标弹起 就是移除移动事件document.addEventListener('mouseup',function(e){document.removeEventListener('mousemove',moeve)})})</script>
</body>
</html>