码迷,mamicode.com
首页 > 其他好文 > 详细

div拖拽

时间:2017-03-16 16:18:56      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:als   var   clientx   移动   目标   default   pos   element   body   

分析逻辑关于该过程有一下3个动作

1、点击 2、移动 3、释放鼠标

 

1、点击时获得点击下去的一点的坐标(盒子的top,left),去除默认事件。

2、移动时不断改变盒子的坐标。(移动的dom目标应该为document不然容易被甩出去)。

3、鼠标释放。清除document的时间。还有改变位置。

4、注意如果鼠标在点击目标时速度太快离开了目标,要马上纠正。

 

写了个简单的方法:

<style type="text/css">
*{margin: 0; padding: 0;}
 #box{width: 300px; height: 200px; border:1px solid #999; position: fixed; top: 20px; left: 20px;}  
 #header{width: 100%; height: 50px; background-color: #999;} 
</style>
<body>
<div id="box">
    <div id="header"></div>
    <div>
        <p>2222222222222222222222222222222121212121212</p>
        <p>2222222222222222222222222222222121212121212</p>
        <p>2222222222222222222222222222222121212121212</p>
        <p>2222222222222222222222222222222121212121212</p>
        <p>2222222222222222222222222222222121212121212</p>
    </div>
</div>
<script type="text/javascript">
var box = document.getElementById(‘box‘);
var header = document.getElementById(‘header‘);
function fnDrap(select,context) {
    var isDown = false;
    var point = {x:0,y:0}
    function windowToBox(x, y) {
        var bbox = select.getBoundingClientRect();///canvas的包围盒的信息
        return {x:x-bbox.left , y:y-bbox.top}
    }
    select.onmousedown = function (e) {
        e.preventDefault();//阻止默认事件,取消文字选中 
        isDown = true;
        point = windowToBox(e.clientX , e.clientY);
        if(!e){
            e = window.event;
            //防止IE文字选中
            context.onselectstart = function(){
                return false;
            }  
        }
        document.onmousemove = function(e) {
            if(isDown) {
                context.style.top =(e.clientY - point.y)+‘px‘;
                context.style.left = (e.clientX - point.x)+‘px‘;
            }
        }
        select.onmouseout = function(e) {
            if(isDown) {
                context.style.top =(e.clientY - point.y)+‘px‘;
                context.style.left = (e.clientX - point.x)+‘px‘;
            }
        }
        select.onmouseup = function (e) {
            isDown = false;
            fnClear();
        }
    }

    function fnClear() {
        select.onmouseup = null;
        document.onmousemove = null;
    }

}
fnDrap(header,box);
</script>

  

div拖拽

标签:als   var   clientx   移动   目标   default   pos   element   body   

原文地址:http://www.cnblogs.com/matthew9298-Begin20160224/p/6559942.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!