js div拖拽示例

来源:互联网 发布:手机淘宝怎样上架宝贝 编辑:程序博客网 时间:2024/06/05 13:25
<!doctype html><html lang="en"> <head>  <meta charset="UTF-8">  <meta name="Generator" content="EditPlus®">  <meta name="Author" content="">  <meta name="Keywords" content="">  <meta name="Description" content="">  <title>div拖拽示例</title>  <style>.div-box{width: 320px;height: 55px;margin: auto;background: #ddd;position: absolute;padding: 30px;                cursor: move;text-align: center;}  </style> </head> <body ><div class="div-box" id="div-box"></div>  <script type="text/javascript">var startX,//鼠标开始横坐标startY,//鼠标开始纵坐标endX,//鼠标结束移动横坐标endY,//鼠标结束移动纵坐标_left,//元素初始横坐标_top;//元素初始纵坐标var _drag=false;//绑定鼠标移动事件document.onmousemove=function(e){var movX,movY;var movBX,movBY;e=e||window.event;movX=e.screenX;//相对于屏幕movY=e.screenY;//相对于屏幕movBX=e.clientX;//相对于浏览器movBY=e.clientY;//相对于浏览器//记录鼠标结束位置endX=movBX;endY=movBY;console.log('鼠标移动_drag:'+_drag);//如果拖拽if(_drag){var divDom=$("div-box");//console.log('_left='+_left+';_top='+_top);//console.log('_left='+(_left+(endX-startX))+';_top='+(_top+(endY-startY)));//endX-startX:横坐标位移量//endY-startY:纵坐标位移量divDom.style.left=(_left+(endX-startX))+'px';divDom.style.top=(_top+(endY-startY))+'px';}$("div-box").innerHTML= '相对于屏幕:movX='+movX+';movY='+movY+ '<br/>相对于浏览器:movX='+movBX+';movY='+movBY;}//鼠标按下事件,获取鼠标坐标$('div-box').onmousedown=function(e){e=e||window.event;startX=e.clientX;//横坐标startY=e.clientY;//纵坐标var divDom=$("div-box");_left=parseInt(divDom.style.left);_top=parseInt(divDom.style.top);if(isNaN(_left)){_left=0}if(isNaN(_top)){_top=0}_drag=true;//console.log('鼠标按下_drag:'+_drag);};document.onmouseup=function(){_drag=false;//console.log('鼠标弹起_drag:'+_drag);};//获得对象function $(id){return document.getElementById(id);}/*document.onmousemove=function(e){var movX,movY;var movBX,movBY;e=e||window.event;movX=e.screenX;//相对于屏幕movY=e.screenY;//相对于屏幕movBX=e.clientX;//相对于浏览器movBY=e.clientY;console.log('movX='+movX);console.log('movY='+movY);document.getElementById("div-box").innerHTML= '相对于屏幕:movX='+movX+';movY='+movY+ '<br>相对于浏览器:movX='+movBX+';movY='+movBY;;}function getMouseMov(e){e=e||window.event;startX=e.clientX;//横坐标startY=e.clientY;//纵坐标return '{"x":"'+x'","y":"'+y+'"}';};*/  </script> </body></html>

0 0
原创粉丝点击