dom 拖拽div

时间:2023-03-09 01:54:48
dom 拖拽div
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
#div1{
width:100px;
height:100px;
background:red;
position:absolute;
}
</style>
<script>
window.onload = function ()
{
var odiv = document.getElementById('div1'); odiv.onmousedown = function (ev)
{
var ev = ev || event;
var dix = ev.clientX - this.offsetLeft;
var diy = ev.clientY - this.offsetTop;
document.onmousemove = function (ev)
{
var ev = ev || event;
odiv.style.top = ev.clientY - diy + 'px';
odiv.style.left =ev.clientX - dix + 'px';
} document.onmouseup = function ()
{
document.onmousedown = document.onmousemove = null;
}
}
}
</script>
</head> <body>
<div id="div1"></div>
</body>
</html>