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>

 

posted @ 2015-01-16 17:58  mayufo  阅读(181)  评论(0编辑  收藏  举报