拖拽——带框

断了今生、忘了曾经 提交于 2019-12-27 05:19:16

<!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>

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!