space line
space line
space line
space line
space line
您现在的位置是: Javascript基础>>

JS鼠标拖动drag函数

发布日期 2008-10-20 7:39:59
作者 shemily
出处 重用网
浏览次数 ...
今日浏览 ...
本月浏览 ...
我要留言 我要留言
space line
摘要
Javascript鼠标拖动drag函数
space line
详细内容

函数体如下:

//----div drag----
function drag(div){
 div.onmousedown=function(a){
  //change div background color
  //div.style.backgroundColor = "#0080C0";

  var d=document;
  var e=d.body?d.body:d.documentElement;
  if(!a)a=window.event;
  var x=a.layerX?a.layerX:a.offsetX,
      y=a.layerY?a.layerY:a.offsetY;
  if(div.setCapture){
   div.setCapture();
  }
  else if(window.captureEvents){
   window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);
  }

  d.onmousemove=function(a){
   if(!a)a=window.event;
   var ex = a.clientX?a.clientX:a.pageX,
       ey = a.clientY?a.clientY:a.pageY;
   
   var scrollY = e.scrollTop;
   var scrollX = e.scrollLeft;

   var tx=ex-x+scrollX,
       ty=ey-y+scrollY;

   if(x<25){ //debug with small width
    //alert(x);
    //return false;
    var w=parseInt((div.style.width).replace("px","")),
           h=parseInt((div.style.height).replace("px",""));
    //tx=ex-x+scrollX-2*w;
    //ty=ey-y+scrollY-3*h;
    return false;
   }

   div.style.left=tx;
   div.style.top=ty;
  };

  d.onmouseup=function(){
   //change back div background color
   //div.style.backgroundColor = "#00A3F0";

   if(div.releaseCapture)
    div.releaseCapture();
   else if(window.captureEvents)
    window.captureEvents(Event.MOUSEMOVE|Event.MOUSEUP);
   d.onmousemove=null;
   d.onmouseup=null;
  };
 };
}

调用方法如:

drag(document.getElementById(´test´));

其中test是div的id;

 

space line
我要留言 我要留言    
space line
space line
space line
space line
赞助商提供
space line
space line