HTML DOM-->拖拽效果
实现:按下鼠标拖动,盒子跟着一起移动
代码如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>js_excise</title> <style type="text/css"> body{ position: relative; } div{ width: 100px; height: 100px; position: absolute; background: palegreen; } </style> </head> <body> <div id="box"></div> <script type="text/javascript"> //获取元素节点 var jsBOX = document.getElementById(‘box‘) //定义坐标 var baseX = 0; var baseY = 0; var moveX = 0; var moveY = 0; //鼠标按下事件 jsBOX.addEventListener(‘mousedown‘,function(e){ var e1 = e || window.event //获取鼠标按下位置 baseX = e1.pageX baseY = e1.pageY console.log(baseX,baseY) //鼠标移动事件 document.onmousemove= function(e){ var e2 = e || window.event //鼠标移动后的位置 moveX = e2.pageX - baseX moveY = e2.pageY - baseY baseX = e2.pageX baseY = e2.pageY console.log(baseX,baseY) //移动后盒子位置 jsBOX.style.left = jsBOX.offsetLeft + moveX + ‘px‘ jsBOX.style.top = jsBOX.offsetTop + moveY + ‘px‘ } },false) //鼠标抬起事件-->清掉移动事件 document.addEventListener(‘mouseup‘,function(){ document.onmousemove = null },false) </script> </body> </html>
输出:
相关推荐
lupeng 2020-11-14
sjcheck 2020-11-10
sjcheck 2020-11-03
meylovezn 2020-08-28
owhile 2020-08-18
Francismingren 2020-08-17
pythonclass 2020-07-29
sunzhihaofuture 2020-07-19
爱读书的旅行者 2020-07-07
行吟阁 2020-07-05
tianqi 2020-07-05
行吟阁 2020-07-04
冰蝶 2020-07-04
lyg0 2020-07-04
owhile 2020-07-04
opspider 2020-06-28
lengyu0 2020-06-28
tianqi 2020-06-21
dadaooxx 2020-06-16