JS 实现拖动效果

<html>
<body style="margin:0px;">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<div id="drag" style="width:100px; height:100px; background-color:red; z-index:1"></div>
<div id="drop" style="width:200px; height:200px;background-color:blue; top:100px; position:absolute;"></div>
<script>
var 
ev , 
dragObj = null ,
dragpos , 
tArr = [] , 
oriLoc = {} , 
canMove = true;
Number.prototype.NaN0 = function(){ return isNaN(this) ? 0 : this; };
function mouseMove(ev){
    ev   = ev || window.event;
    var mp = getEvLoc(ev);
    if(dragObj && canMove){
        dragObj.style.position = 'absolute';
        dragObj.style.top      = mp.y - dragpos.y;
        dragObj.style.left     = mp.x - dragpos.x;
    }
}

function mouseDown(ev){
    ev = ev || window.event;
    var t = ev.target || ev.srcElement;
    if( t.id == 'drag' ){
        dragObj = t;
        canMove = true;
        dragpos = getOffset(t ,ev);
        return false;
    }
}

function getOffset( t, ev  ){

    var po = getEvLoc( ev );
        oriLoc = getPosition( t );
    return  {x: (po.x - oriLoc.x), y: (po.y - oriLoc.y) };

}

function mouseUp(ev){
    if(!dragObj) 
        return false;
    ev = ev || window.event;
    var mp = getEvLoc(ev) , canDrop = false;
    for(var i in tArr){
        var tempTar = tArr[i];
        var tp =  getPosition(tArr[i]);
        var tw = tempTar.offsetWidth;
        var th = tempTar.offsetHeight;
        if( mp.x > tp.x && mp.x < (tp.x + tw) && mp.y > tp.y && mp.y < (tp.y + th) ){
            canDrop = true;
        }
    }
    if(!canDrop){
        canMove = false;
        dragObj.style.position = 'relative';
        dragObj.style.top      = oriLoc.y;
        dragObj.style.left     = oriLoc.x;
    }
    dragObj = null;
    return false;
}
function getEvLoc( ev ){
    if(ev.pageX || ev.pageY){
        return { x:ev.pageX, y: ev.pageY};
    }
    return {
        x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
        y:ev.clientY + document.body.scrollTop  - document.body.clientTop
    };
}

function getPosition( e ){
    var left = 0;
    var top  = 0;
    while (e.offsetParent){
        left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
        top  += e.offsetTop  + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);
        e     = e.offsetParent;
    }

    left += e.offsetLeft + (e.currentStyle?(parseInt(e.currentStyle.borderLeftWidth)).NaN0():0);
    top  += e.offsetTop  + (e.currentStyle?(parseInt(e.currentStyle.borderTopWidth)).NaN0():0);

    return {x:left, y:top};

}

function addDropTarget( obj ){
    tArr.push(obj);
}

addDropTarget(document.getElementById('drop'));
document.onmousedown = mouseDown;
document.onmousemove = mouseMove;
document.onmouseup   = mouseUp;
</script>

</body>
</html>

 后续功能做成插件形式~ 

posted @ 2014-03-18 09:26  ﹏Sakura  阅读(348)  评论(0编辑  收藏  举报