关于鼠标拖动物体原理的学习笔记1
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style type="text/css">
*{margin:0;padding:0;}
.box{width:100px;height:100px;background: red;position: absolute;left:0;top:0;}
    </style>
</head>
<body>
    <div class="box"></div>
    <script type="text/javascript">
var o=document.querySelector('.box');
var l,t;
o.onmousedown=function (ev){
    var ev=ev||event;
    var target=ev.target||ev.srcElement;
    l=ev.clientX-o.offsetLeft;
    t=ev.clientY-o.offsetTop;
    document.onmousemove=function (ev){
        o.style.top=ev.clientY-t+'px';
        o.style.left=ev.clientX-l+'px';
    };
    document.onmouseup=function (){
        document.onmousemove=null;
    };
};
    </script>
</body>
</html>
鼠标拖动物体的原理,前提是物体要是具有定位属性,当鼠标按下onmousedown时,获取鼠标event对象的坐标,减去物体左上角的坐标,得到鼠标按下的位置,当鼠标按下并移动时,计算并设置物体的动态坐标,鼠标抬起时清空鼠标事件,再次按下时重新获取。
                    
                
                
            
        
浙公网安备 33010602011771号