オリジナルのJavaScriptのドラッグ方法を共有します.

3127 ワード

コード:

function drag(t,p){

  var point = p || null,
    target = t || null,
    resultX = 0,
    resultY = 0;

  (!point)? point = target : ''; //       ,              

  function getPos(t){
    var offsetLeft = 0,
      offsetTop = 0,
      offsetParent = t;

    while(offsetParent){
      offsetLeft+=offsetParent.offsetLeft;
      offsetTop+=offsetParent.offsetTop;
      offsetParent = offsetParent.offsetParent;
    }

    return {'top':offsetTop,'left':offsetLeft};
  }

  function core(){

    var width = document.body.clientWidth || document.documentElement.clientWidth,
      height = document.body.clientHeight || document.documentElement.clientHeight; 
      maxWidth = width - target.offsetWidth,
      maxHeight = height - target.offsetHeight;

    (resultX >= maxWidth)? target.style.left = maxWidth+'px' : (resultX > 0)?target.style.left = resultX +'px': ''; //      。
    (resultY >= maxHeight)?  target.style.top = maxHeight +'px' : (resultY > 0)?target.style.top = resultY +'px':''; //      。

    point.onmousedown=function(e){  
      var e = e || window.event,
        coordX = e.clientX,
        coordY = e.clientY,
        posX = getPos(target).left,
        posY = getPos(target).top;

      point.setCapture && point.setCapture();  // Mouse          。
      document.onmousemove=function(e){

        var ev = e || window.event,
          moveX = ev.clientX,
          moveY = ev.clientY;

        resultX = moveX - (coordX - posX); //                        
        resultY = moveY - (coordY - posY);

        (resultX > 0 )?((resultX < maxWidth)?target.style.left = resultX+'px' : target.style.left = maxWidth+'px') : target.style.left = '0px'; 
        (resultY > 0 )?((resultY < maxHeight)?target.style.top = resultY+'px' : target.style.top = maxHeight+'px') : target.style.top = '0px'; 

        ev.stopPropagation && ev.stopPropagation(); 
        ev.preventDefault;
        ev.returnValue = false;
        ev.cancelBubble = true;
      };
    };
    document.onmouseup=function(){  //      ,      DOM         ,        onmousedown BUG。
      document.onmousemove = null;  
      point.releaseCapture && point.releaseCapture();  //  Mouse          。
    };
    point.onmouseup=function(e){
      var e = e || window.event;
      document.onmousemove = null;
      point.releaseCapture && point.releaseCapture();
    };
  }
  core();
  window.onresize = core;  
}

使い方:

 drag(t,p)
 /* 
 *    
 * t         
 * p      
 */
 
 //   :       ,