DOM特效模拟框拖拽
拖拽原理
1:mousedown 鼠标按压获取鼠标在登录框的宽度。
2:mousemove 鼠标移动的时获取最新的pageX减去鼠标在登录框的X距离,就是模态框的left与top值。
3:mouseup 鼠标松开时,移除mousemove 事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
#shadow{
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
background-color: #000;
opacity: .3;
display: none;
z-index: 10;
}
.login{
width: 400px;
height: 240px;
border: 2px solid #666;
padding: 0 10px;
position: fixed;
left: 50%;
top: 50%;
margin-left: -200px;
margin-top: -120px;
z-index: 20;
display: none;
background-color: #fff;
box-sizing: border-box;
}
.title{
width: 100%;
height: 40px;
line-height: 40px;
}
.title>span{
float: right;
cursor: pointer;
}
.in{
width: 300px;
height: 120px;
line-height: 40px;
margin: 20px auto;
padding: 20px;
box-sizing: border-box;
}
#btn{
position: absolute;
left: 50px;
top: 30px;
}
</style>
</head>
<body>
<button id="btn">登录</button>
<div id="shadow"></div>
<div class="login">
<div class="title">登录 <span>关闭</span></div>
<div class="in">
用户名<input type="text"><br>
密码<input type="password">
</div>
</div>
<script>
var btn=document.getElementById("btn")
var shadow=document.getElementById("shadow")
var login=document.querySelector(".login")
var tclose=document.querySelector(".title>span")
btn.addEventListener("click",function(){
shadow.style.display="block"
login.style.display="block"
btn.style.display="none"
})
tclose.addEventListener("click",function(){
shadow.style.display="none"
login.style.display="none"
btn.style.display="block"
})
login.addEventListener("mousedown",function(e){
var lx=e.pageX-this.offsetLeft
var ly=e.pageY-this.offsetTop
document.addEventListener("mousemove",move)
function move(e){
var x=e.pageX+200-lx
var y=e.pageY+120-ly
login.style.left=x+"px"
login.style.top=y+"px"
}
login.addEventListener("mouseup",function(){
document.removeEventListener("mousemove",move)
})
})
</script>
</body>
</html>
实验截图: