动态拖拽盒子的方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
background-color: #CCC;
}
.login {
width: 512px;
height: 280px;
position: fixed;
border: #ebebeb solid 1px;
left: 50%;
top: 50%;
background-color: #fff;
box-shadow: 0px 0px 20px #ddd;
z-index: 9999;
transform: translate(-50%,-50%);
}
.login-title {
width: 100%;
margin: 0px 0px 20px #ddd;
text-align: center;
line-height: 40px;
font-size: 18px;
height: 40px;
position: relative;
cursor:move;
}
.login-input-content{
margin-top: 20px;
}
.login-button {
width:50%;
margin:30px auto 0px auto;
line-height: 40px;
}
</style>
</head>
<body>
<div class="login-header"><a id="link" href="javascript:;">点击,弹出登录框</a></div>
<div class="login" id="login">
<div id="title" class="login-title">登陆会员
<span><a id="closeBtn" href="javascript:viod(0);" class="close-login">关闭</a></span>
</div>
<div class="login-input-content">
<div class="login-input">
<label>用户名:</label>
<input type="text" placeholder="请输入用户名" name="info[username]" id="username">
</div>
<div class="login-input">
<label>登陆密码</label>
<input type="password" placeholder="请输入登陆密码" name="info[password]" id="password">
</div>
</div>
<div id="loginBtn" class="login-button"><a href="javascript:void(0);" id="login-button-submit"></a></div>
</div>
<!-- 遮盖层 -->
<div id="bg" class="login-bg"></div>
<script>
// 1 获取元素
var login = document.querySelector('.login')
var mask = document.querySelector('.login-bg')
var link = document.querySelector('#link');
var title =document.querySelector('#title')
var closeBtn = document.querySelector('#closeBtn');
// 2 点击弹出层的这个链接link 让mask 和 login显示出来
link.addEventListener('click',function(){
mask.sytle.display = 'block'
login.style.display = 'block'
})
// 3点击了closeBtn就隐藏mask和 login
closeBtn.addEventListener('click', function(){
mask.style.display = 'none'
login.style.dispaly = 'none'
})
// 4 拖拽开始
//(1) 当我们按下鼠标时,就获得鼠标在盒子内的坐标
title.addEventListener('mousedown', function(e){
var x = e.pageX - login.offsetleft;
var y = e.pageY -login.offsetTop;
// (2) 鼠标移动的时候,把鼠标在页面中的坐标减去鼠标在盒子中的坐标
document.addEventListener('mousemove',move)
function move(e){
login.style.left = e.pageX - x + 'px';
login.style.top = e.pageY - y + 'px'
}
// (3) 鼠标弹起,就让移动事件移除
document.addEventListener('mouseup', function() {
document.removeEventListener('mousemove', move)
})
})
</script>
</body>
</html>