原生JS实现窗口拖拽效果
按住鼠标按键,可以实现注册窗口自由拖拽效果;
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
* {
margin: 0;
padding: 0;
}
.nav {
height: 30px;
background: #87cefa;
line-height: 30px;
padding-left: 30px;
}
.nav a {
color: #fff;
text-align: center;
font-size: 14px;
text-decoration: none;
}
.d-box {
width: 400px;
height: 300px;
border: 5px solid #eee;
box-shadow: 2px 2px 2px 2px #666;
position: absolute;
top: 50%;
left: 50%;
background-color: white;
/* 不让文字被选中 */
user-select: none;
transform: translate(-50%, -50%);
}
.hd {
width: 100%;
height: 35px;
background-color: #87cefa;
border-bottom: 1px solid #369;
line-height: 35px;
color: white;
cursor: move;
}
#box_close {
float: right;
cursor: pointer;
}
</style>
</head>
<body>
<div class="nav">
<a href="javascript:;" id="register">注册信息</a>
</div>
<div class="d-box" id="d_box">
<div class="hd" id="drop">注册信息 (可以拖拽)
<span id="box_close">【关闭】</span>
</div>
<div class="bd"></div>
</div>
<script>
// 获取盒子
var box = document.getElementById('d_box');
// 获取盒子标题区块
var drop = document.getElementById('drop');
drop.onmousedown = function (e) {
// 兼容性处理
var e = e || window.event;
// 当鼠标在盒子标题区域按下的时候,获取鼠标在盒子里面的下标
// 鼠标在盒子的下标 = 鼠标在页面的的下标 - 盒子的偏移量;
var x = e.pageX - box.offsetLeft;
var y = e.pageY - box.offsetTop;
console.log(x + " " + y);
document.onmousemove = function (e) {
// 兼容性处理
var e = e || window.event;
// 当鼠标在页面上移动的时候。求盒子的坐标
// 盒子的坐标 = 鼠标当前在页面中的位置 - 鼠标在盒子中的位置
var boxX = e.pageX - x;
var boxY = e.pageY - y;
box.style.left = boxX + "px";
box.style.top = boxY + "px";
}
}
// 当鼠标在页面文档中弹起,移除移动跟随
document.onmouseup = function () {
document.onmousemove = null;
}
// 点击关闭按钮,隐藏盒子
var box_close = document.getElementById('box_close');
box_close.onclick = function () {
box.style.display = 'none';
}
</script>
</body>
</html>
还没有评论,来说两句吧...