<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>拖拽</title>
<style type="text/css">
*{
margin:0px;
padding:0px;
}
body{
-webkit-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none;
}
#main2 {
width: 100%;
height: 900px;
position: relative;
}
#box2{
width: 600px;
height: 400px;
background-color: #fc0;
position: absolute;
left: 450px;
top: 200px;
text-align: center;
font-size: 20px;
line-height: 100px;
}
</style>
</head>
<body>
<div id="main2">
<div id="box2">
<div id="box2_header" style="width:100%;height:40px;line-height: 40px;background-color:#787878;cursor:move;color:white;">我是窗口头部,拖拽我可以移动</div>
</div>
</div>
</body>
<script type="text/javascript">
var box2 = document.getElementById("box2");
var main2 = document.getElementById("main2");
var box2_header = document.getElementById("box2_header");
Drags(box2_header,box2,main2)
//封装拖拽方法
function Drags(childre_n,fathe_r,fathe_r_father){
childre_n.onmousedown = function (event){//头部鼠标按下的时候
var event = event || window.event;//浏览器兼容
//鼠标最初点按位置
var mousex = event.clientX;//获取鼠标的初始X位置
var mousey = event.clientY;//获取鼠标的初始Y位置
//获取div距离外部组件的间距 left
var fathe_r_left = fathe_r.offsetLeft;//获取的是当前对象左侧距离父对象左侧的值(均不包含border);
var fathe_r_top = fathe_r.offsetTop;//获取的是当前对象最顶端距离父对象最顶端的值(均不包含border);
document.onmousemove = function (event){//当鼠标松开的时候
var event = event || window.event;//浏览器兼容
var mousexnow = event.clientX;//获取相对文档的水平座标
var mouseynow = event.clientY;//获取相对文档的垂直座标
//组件初始距离左侧间距box2_left + (鼠标结束时位置 - 鼠标开始时水平位置)
var left2 = fathe_r_left + (mousexnow - mousex);
var top2 = fathe_r_top + (mouseynow - mousey);
if (left2<=0) {
left2 = 0;
}
if (top2<=0) {
top2 = 0;
}
//clientWidth可见区域宽 clientHeight可见区域宽
if (left2 >= fathe_r_father.clientWidth - fathe_r.clientWidth) {
left2 = fathe_r_father.clientWidth - fathe_r.clientWidth;
}
if (top2>=fathe_r_father.clientHeight - fathe_r.clientHeight) {
top2=fathe_r_father.clientHeight - fathe_r.clientHeight;
}
//改变left与top值
fathe_r.style.left = left2 + "px";
fathe_r.style.top = top2 + "px";
}
//当松开鼠标的时候
document.onmouseup = function(){
document.onmousemove = null;
}
}
}
</script>
</html>