<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style type="text/css">
.all {
height: 300px;
width: 450px;
border: 2px solid black;
position: absolute;
}
.top {
height: 20%;
width: 100%;
background: pink;
}
.a {
height: 100%;
width: 100%;
border: 1px solid blue;
}
</style>
<script>
function getClassName(clsName, Parent) {
var Parent = Parent ? document.getElementById(Parent) : document,
eles = [],
elements = Parent.getElementsByTagName("*");
for (var i = 0; i < elements.length; i++) {
if (clsName == elements[i].className) {
eles.push(elements[i]);
}
}
return eles;
}
window.onload = drag;
function drag() {
//获取className=top的对象
var pannel = getClassName("top", "all")[0];
//当鼠标点击时触发
alert(pannel.innerHTML);
document.title = "111";
pannel.onmousedown = fndrag;
}
function fndrag(event) {
document.title = "222";
var all = document.getElementById("all");
var pannel = getClassName("top", "all")[0];
var event = event || window.event;
//获取鼠标距离窗口的位置
var disX = event.clientX - all.offsetLeft;
var disY = event.clientY - all.offsetTop;
//鼠标移动
document.onmousemove = function (event) {
var e = event || window.event;
pannel.style.cursor = "move";
fnmove(e, disX, disY);
}
//放开鼠标
document.onmouseup = function () {
document.onmouseup = null;
document.onmousemove = null;
pannel.style.cursor = "auto";
}
}
function fnmove(e, disX, disY) {
//获取窗口的位置(左上角)
var l = e.clientX - disX;
var t = e.clientY - disY;
var all = document.getElementById("all");
//获取可视窗口的长宽,兼容浏览器
var winWid = document.documentElement.clientWidth || document.body.clientWidth;
var winHei = document.documentElement.clientHeight || document.body.clientHeight;
//获取窗口的最大宽度和长度(左上角)
var maxWid = winWid - all.offsetWidth - 10;
var maxHei = winHei - all.offsetHeight - 10;
//超出左边间距
if (l < 0) {
l = 10;
}
//超出右边间距
else if (l > maxWid) {
l = maxWid;
}
//超出上面距离
if (t < 0) {
t = 10;
}
else if (t > maxHei) {
t = maxHei;
}
document.title = l + "," + t;
all.style.left = l + "px";
all.style.top = t + "px";
}
</script>
<body>
<div class="a">
<div id="all" class="all">
<div class="top">鼠标点击区域</div>
</div>
</div>
</body>
</html>