美文网首页深究JavaScript
原生js实现简易拖拽

原生js实现简易拖拽

作者: Funwt | 来源:发表于2017-10-26 21:38 被阅读19次
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
        <div id="container">
        </div>
    </body>
</html>
#container{
  position:relative;
  width: 50px;
  height: 50px;
  cursor: move;
  background: blue;
  top:60px;
  left:60px;
}
var c = document.getElementById("container");
function drag(o){
                var left,top,x,y,flag;
                o.onmousedown = function(e){
                    x = e.clientX;
                    y = e.clientY;
                    left =  parseInt(getComputedStyle(o,null).left);
                    top = parseInt(getComputedStyle(o,null).top);
                    flag = true;
                }
                document.onmouseup = function(){
                    flag = false;
                }
                document.onmousemove = function(e){
                    if(flag){
                        var tx = e.clientX;
                        var ty = e.clientY;
                        o.style.left = left + tx -x + 'px';
                        o.style.top = top + ty - y + 'px';
                        console.log(tx,ty);
                    }   
                }
            }
            drag(c);

相关文章

网友评论

    本文标题:原生js实现简易拖拽

    本文链接:https://www.haomeiwen.com/subject/ktrlpxtx.html