<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>拖拽窗口实现</title>
<style>
* {
margin: 0;
padding: 0;
}
.nav {
height: 30px;
background: #036663;
border-bottom: 1px solid #369;
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: 40%;
left: 40%;
background-color: white;
/* 不让文字被选中
-webkit-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none; */
}
.hd {
width: 100%;
height: 25px;
background-color: #7c9299;
border-bottom: 1px solid #369;
line-height: 25px;
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');
// 获取页面滚动距离的浏览器兼容性问题
// 获取页面滚动出去的距离
function getScroll() {
var scrollLeft = document.body.scrollLeft || document.documentElement.scrollLeft;
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
return {
scrollLeft: scrollLeft,
scrollTop: scrollTop
}
}
// 获取鼠标在页面的位置,处理浏览器兼容性
function getPage(e) {
var pageX = e.pageX || e.clientX + getScroll().scrollLeft;
var pageY = e.pageY || e.clientY + getScroll().scrollTop;
return {
pageX: pageX,
pageY: pageY
}
}
drop.onmousedown = function (e) {
// 兼容性处理
e = e || window.event;
// 当鼠标按下的时候,求鼠标在盒子中的位置
// 鼠标在盒子中的位置 = 鼠标在页面上的位置 - 盒子的位置
var x = getPage(e).pageX - box.offsetLeft;
var y = getPage(e).pageY - box.offsetTop;
// 鼠标在文档中移动
document.onmousemove = function (e) {
e = e || window.event;
// 当鼠标在页面上移动的时候。求盒子的坐标
// 盒子的坐标 = 鼠标当前在页面中的位置 - 鼠标在盒子中的位置
var boxX = getPage(e).pageX - x;
var boxY = getPage(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>
拖拽窗口实现
猜你喜欢
转载自blog.csdn.net/qq_38233172/article/details/89791790
今日推荐
周排行