<!DOCTYPE html>

<html>

 

<head>

<meta charset="UTF-8">

<title></title>

<style type="text/css">

#box {

height: 300px;

width: 300px;

background-color: green;

position: absolute;

left: 0;

top: 0;

}

 

.border {

border: 2px dashed red;

position: absolute;

}

</style>

</head>

 

<body>

<div id="box">

 

</div>

</body>

<script type="text/javascript">

var box = document.getElementById("box");

var x = 0;

var y = 0;

box.onmousedown = function(ev) {

var oEvent = ev || event;

x = oEvent.clientX - box.offsetLeft;

y = oEvent.clientY - box.offsetTop;

//产生一个新的div,即为拖拽的框

var div = document.createElement("div");

div.className = "border";

div.style.width = box.offsetWidth + "px";

div.style.height = box.offsetHeight + "px";

div.style.left = box.offsetLeft + "px";

div.style.top = box.offsetTop + "px";

document.body.appendChild(div)

//鼠标移动的函数

document.onmousemove = function(ev) {

var oEvent = ev || event;

 

var L = oEvent.clientX - x;

var T = oEvent.clientY - y;

 

div.style.left = L + "px";

div.style.top = T + "px";

}

//鼠标抬起的函数

document.onmouseup = function() {

this.onmousemove = null;

this.onmouseup = null;

box.style.left = div.offsetLeft + "px";

box.style.top = div.offsetTop + "px";

document.body.removeChild(div);

}

 

return false;

 

}

</script>

 

</html>

posted on 2016-12-03 22:03  代码小公主  阅读(240)  评论(0编辑  收藏  举报