描述:用户在弹出窗口的特定区域点击鼠标左键之后,可以对弹出的窗口进行拖拉,鼠标移开之后,窗口固定在最终的位置,点击关闭按钮,就可以关闭弹出的窗口。
实现代码:
<!DOCTYPE html>
<html lang="en">
<head>
<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%;
}
.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>
</body>
</html>
<script>
var box = document.getElementById("d_box");//需要移动的盒子
var drop = document.getElementById("drop");//需要拖拽的盒子
var box_close = document.getElementById("box_close");//关闭按钮
startDrop(drop,box);
/**
* 鼠标拖动函数
* @param obj 需要拖拽的盒子
* @param target 需要移动的盒子
*/
function startDrop(obj,target) {
obj.onmousedown = function (event) {
var event = event || window.event;
//鼠标的位置
var pagey = event.pageY||event.clientY+document.documentElement.scrollTop;//documentElement文本元素的根节点
var pagex = event.pageX || event.clientX+document.documentElement.scrollLeft;
//鼠标在盒子中的位置
var x = pagex -target.offsetLeft;
var y = pagey - target.offsetTop;
//盒子的移动
document.onmousemove = function (event) {
var event = event||window.event;
//移动后鼠标的位置
var pageym = event.pageY||event.clientY+document.documentElement.scrollTop;
var pagexm = event.pageX|| event.clientX+document.documentElement.scrollLeft;
//目标位置
var xx = pagexm - x;
var yy = pageym - y;
//移到的位置
target.style.left = xx+"px";
target.style.top = yy+"px";
//清除选中的文字
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
}
}
document.onmouseup = function () {
document.onmousemove = null;
}
}
box_close.onclick = function () {
box.style.display = "none";
}
</script>