JS 拖拽原理

涉及拖拽就会涉及到这三个 方法:touchstart 、touchmove、 touchend




1.当touchstart时记录 :x点的(x,y)坐标,同时记录下距离o 左边(dragLeft)与上边(dragTop)的边距offsetLeft ,offsetTop.

2.touchmove时  ,记录当前移动的坐标(x1,y1),并且拖拽距离为 :x1-x+dragLeft;    Y 坐标同理;



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题文档</title>
    <style type="text/css">
        *{ margin:0; padding:0;}
        #dragDiv{ width:200px; height:200px; position:absolute; top:100px; left:100px; background:#ddd;}
    </style>
</head>

<body>
<div id="dragDiv"></div>
<script type="text/javascript">
    var dragDiv=document.getElementById('dragDiv');
    //鼠标按下动作
    dragDiv.οnmοusedοwn=function(event){
        dragDiv.style.cursor="move";
        var e=event||window.event,
                t=e.target||e.srcElement,
        //鼠标按下时的坐标x1,y1
                x1=e.clientX,
                y1=e.clientY,
        //鼠标按下时的左右偏移量
                dragLeft=this.offsetLeft,
                dragTop=this.offsetTop;
        document.onmousemove=function(event){
            var e=event||window.event,
                    t=e.target||e.srcElement,
            //鼠标移动时的动态坐标
                    x2=e.clientX,
                    y2=e.clientY,
            //鼠标移动时的坐标的变化量
                    x=x2-x1,
                    y=y2-y1;
            dragDiv.style.left=(dragLeft+x)+'px';
            dragDiv.style.top=(dragTop+y)+'px';
           // dragDiv.style.left=(dragLeft+x)+'px';
           // dragDiv.style.top=(dragTop+y)+'px';
        }
        document.onmouseup=function(){
            this.onmousemove=null;
            dragDiv.style.cursor="";
        }
    }
</script>
</body>
</html>

 

来源:http://bbs.blueidea.com/thread-3099351-1-1.html

参考 :http://blog.csdn.net/jiangcs520/article/details/17564065

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值