1:鼠标在元素上的坐标位置 offsetX offsetY 2:鼠标在浏览器(可视窗口)上的坐标位置 clientX clientY 3:事件 onmousedown 鼠标按下 onmousemove 鼠标移动 onmouseup 鼠标弹起 4:可视窗口的宽度和高度 document.documentElement.clientWidth document.documentElement.clientHeight 5:获取元素的宽高 offsetWidth offsetHeight 6:获取元素到浏览器窗口的距离 offsetLeft offsetTop
简单拖拽
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{ margin: 0; padding: 0; } div{ width: 100px; height: 100px; background: pink; margin: 0 auto; } </style> </head> <body> <div id="box"></div> </body> <script type="text/javascript"> // e.offsetX e.offsetY是光标在当前元素上的坐标位置 var obox=document.getElementById('box'); obox.onclick=function(e){ var e=e||window.event; alert(e.offsetX+','+e.offsetY)//65,56 } </script> </html>多个拖拽
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> *{ margin: 0; padding: 0; } #box{ width: 100px; height: 100px; background: pink; position: absolute; } #box1{ width: 100px; height: 100px; background: yellow; position: absolute; } </style> </head> <body> <div id="box"></div> <div id="box1"></div> </body> <script type="text/javascript"> var obox=document.getElementById('box'); var obox1=document.getElementById('box1'); obox.onmousedown=function(e){ var e=e||window.event; x=e.offsetX;//获取光标在div元素的坐标位置 y=e.offsetY; document.onmousemove=function(e){ var e=e||window.event; l=e.clientX-x; t=e.clientY-y; //l是div元素到浏览器左边的距离 //t是div元素到浏览器上边的距离 if(l<0){ l=0; } if(l>document.documentElement.clientWidth-obox.offsetWidth){ l=document.documentElement.clientWidth-obox.offsetWidth; } if(t<0){ t=0; } if(t>document.documentElement.clientHeight-obox.offsetHeight){ t=document.documentElement.clientHeight-obox.offsetHeight; } obox.style.left=l+'px'; obox.style.top=t+'px'; } } obox.onmouseup=function(){ document.onmousemove=0; } obox1.onmousedown=function(e){ var e=e||window.event; x=e.offsetX;//获取光标在div元素的坐标位置 y=e.offsetY; document.onmousemove=function(e){ var e=e||window.event; l=e.clientX-x; t=e.clientY-y; if(l<0){ l=0; } if(l>document.documentElement.clientWidth-obox1.offsetWidth){ l=document.documentElement.clientWidth-obox1.offsetWidth; } if(t<0){ t=0; } if(t>document.documentElement.clientHeight-obox1.offsetHeight){ t=document.documentElement.clientHeight-obox1.offsetHeight; } obox1.style.left=l+'px'; obox1.style.top=t+'px'; } } obox1.onmouseup=function(){ document.onmousemove=0; } </script> </html>