js拖动层代码

来源:互联网 发布:卫宁软件科技有限公司 编辑:程序博客网 时间:2024/05/17 02:42
//how to use
// create a div with the id, then make the action to the div
//ex:
//<div style='position:absolute' id='move_me' onMouseDown="javascript:moveStart(event,'move_me')" >i can move</div>
function $(_sId){return document.getElementById(_sId);}
 function moveStart (event, _sId){
  var oObj = $(_sId);
  oObj.onmousemove = mousemove;
  oObj.onmouseup = mouseup;
  oObj.setCapture ? oObj.setCapture() : function(){};
  oEvent = window.event ? window.event : event;
  var dragData = {x : oEvent.clientX, y : oEvent.clientY};
  var backData = {x : parseInt(oObj.style.top), y : parseInt(oObj.style.left)};
  function mousemove(){
   var oEvent = window.event ? window.event : event;
   var iLeft = oEvent.clientX - dragData["x"] + parseInt(oObj.style.left);
   var iTop = oEvent.clientY - dragData["y"] + parseInt(oObj.style.top);
   oObj.style.left = iLeft;
   oObj.style.top = iTop;
   dragData = {x: oEvent.clientX, y: oEvent.clientY};  
  }
  function mouseup(){
   var oEvent = window.event ? window.event : event;
   oObj.onmousemove = null;
   oObj.onmouseup = null;
   if(oEvent.clientX < 1 || oEvent.clientY < 1 || oEvent.clientX > document.body.clientWidth || oEvent.clientY > document.body.clientHeight){
    oObj.style.left = backData.y;
    oObj.style.top = backData.x;
   }
   oObj.releaseCapture ? oObj.releaseCapture() : function(){};
  }
 }
原创粉丝点击