简单的鼠标拖动效果

使用js实现简单的鼠标拖动效果,但此部分代码有个小小的BUG,后期改进好我会写进来,但基本的效果已经实现,请大家参考。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>鼠标移动</title>
    <style>
    #box{
        width: 50px;
        height: 50px;
        position: relative;
        background-color: green;
        top: 50px;
        left: 50px;
        cursor: move;
    }
    </style>
</head>
<body>
    <div id="box"></div>
    <script>
        var box=document.getElementById('box');
        var x=0,y=0,boxx=0,boxy=0,ex=0,ey=0,isDown=true;
        box.onmousedown=function(ev){
             var e=ev||window.event;
                ex=e.clientX-box.offsetLeft;
                ey=e.clientY-box.offsetTop;
            box.onmousemove=function(ev){
                var e=ev||window.event;
                    x=e.clientX-ex;
                    y=e.clientY-ey;
                    box.style.left=x+'px';
                    box.style.top=y+'px';
                    console.log(x);
                    console.log(y);
            }
         }
         box.onmouseup=function(){
            box.onmousemove='null';
        }
    </script>
</body>
</html>
原文地址:https://www.cnblogs.com/duenyang/p/5819535.html