效果图
思路
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="main" style="background-color: aqua;width: 100px;height: 100px;position: absolute;left: 50px;top: 50px">
<div id="title" style="height: 10px;width:100%;background-color: antiquewhite;position: absolute;left: 0px;top: 0px"></div>
<div class="box"></div>
</div>
<script>
var startx;
var starty;
var startLeft;
var startTop;
var titleDiv=document.getElementById("title");
var mainDiv=document.getElementById("main");
var isDown=false;
function movedown(e){
e=e?e:window.event;
isDown=true;
startx=e.clientX;
starty=e.clientY;
startLeft=parseInt(mainDiv.style.left);
startTop=parseInt(mainDiv.style.top);
}
function move(e){
e=e?e:window.event;
if(isDown) {
mainDiv.style.left = e.clientX - (startx - startLeft)+"px";
mainDiv.style.top = e.clientY - (starty - startTop)+"px";
}
}
function moveup(){
isDown=false;
}
titleDiv.onmousedown=movedown;
titleDiv.onmousemove=move;
titleDiv.onmouseup=moveup;
</script>
</body>
</html>
优化(封装,以及解决拖动问题(事件捕获))
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="main" style="background-color: aqua;width: 100px;height: 100px;position: absolute;left: 50px;top: 50px">
<div id="title"
style="height: 10px;width:100%;background-color: antiquewhite;position: absolute;left: 0px;top: 0px"></div>
<div class="box"></div>
</div>
<script>
function Mover(title) {
this.obj = title;
this.startx = 0;
this.starty;
this.startLeft;
this.startTop;
this.mainDiv = title.parentNode;
var that = this;
this.isDown = false;
this.movedown = function (e) {
e = e ? e : window.event;
if (!window.captureEvents) {
this.setCapture();
}
that.isDown = true;
that.startx = e.clientX;
that.starty = e.clientY;
that.startLeft = parseInt(that.mainDiv.style.left);
that.startTop = parseInt(that.mainDiv.style.top);
}
this.move = function (e) {
e = e ? e : window.event;
if (that.isDown) {
that.mainDiv.style.left = e.clientX - (that.startx - that.startLeft) + "px";
that.mainDiv.style.top = e.clientY - (that.starty - that.startTop) + "px";
}
}
this.moveup = function () {
that.isDown = false;
if (!window.captureEvents) {
this.releaseCapture();
}
}
this.obj.onmousedown = this.movedown;
this.obj.onmousemove = this.move;
this.obj.onmouseup = this.moveup;
document.addEventListener("mousemove", this.move, true);
}
var mover = new Mover(document.getElementById("title"));
</script>
</body>
</html>