<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>拖拽事件</title>
<style>
.nav {
height: 50px;
width: 100%;
background-color: #b1ffe5;
}
#box {
width: 400px;
height: 300px;
border: 5px solid #eee;
box-shadow: 2px 2px 2px 2px #666;
position: absolute;
top: 40%;
left: 40%;
background-color: white;
cursor: move;
/*不让文字被选中*/
-webkit-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none;
}
#drop {
width: 100%;
height: 35px;
background-color: #7c9299;
border-bottom: 1px solid #369;
line-height: 35px;
color: white;
cursor: move;
}
#close {
float: right;
cursor: pointer;
}
* {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
</style>
</head>
<body>
<div class="nav">
<a href="javascript:;" id="re">注册信息</a>
</div>
<div id="box">
<div id="drop">可拖拽这里移动窗口位置
<span id="close" >关闭窗口</span>
</div>
<div class="bd"></div>
</div>
<script>
//获取元素
var box = document.getElementById("box");
var drop = document.getElementById("drop");
var close = document.getElementById("close");
//给drop添加鼠标按下事件,在内部继续绑定一个鼠标移动事件
drop.onmousedown = function(e){
e = e || window.event;
//记忆鼠标按下时,鼠标在父盒子内部的间距
var l = e.pageX - box.offsetLeft;
var t = e.pageY - box.offsetTop;
drop.onmousemove = function(e){
e = e || window.event;
//鼠标移动过程中,可以计算box的left和top
var nowleft = e.pageX - l;
var nowtop = e.pageY - t;
box.style.left = nowleft + "px";
box.style.top = nowtop + "px";
};
};
//鼠标弹起事件
drop.onmouseup = function(){
drop.onmousemove = null;
};
//点击关闭box
close.onclick = function(){
box.style.display = "none";
};
</script>
</body>
</html>