浅析JavaScript动画模拟拖拽原理(2)

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> #box{ width: 100px; height: 100px; background: red; position: absolute; } </style> </head> <body> <div>模拟拖拽</div> <script> var oBox = document.getElementById('box'); oBox.onmousedown = function(ev){ // 鼠标按下 var ev = ev || event; // 获取鼠标离div得距离 var mouseBoxleft = ev.clientX - this.offsetLeft; var mouseBoxTop = ev.clientY - this.offsetTop; // IE浏览器,全局捕获 if(oBox.setCapture){ oBox.setCapture(); } document.onmousemove = function(ev){ // 鼠标按下左键并移动 var ev = ev || event; // 设置div移动时,它的位置 oBox.style.left = ev.clientX - mouseBoxleft + 'px'; oBox.style.top = ev.clientY - mouseBoxleft + 'px'; } document.onmouseup = function(){ // 鼠标左键抬起 document.onmousemove = document.onmouseup = null; //IE下,释放全局捕获 releaseCapture(); if ( oBox.releaseCapture ) { oBox.releaseCapture(); } } // 阻止默认行为 return false; } </script> </body> </html>

【3】封装模拟拖拽函数

 代码:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> #box{ width: 100px; height: 100px; background: red; position: absolute; } </style> </head> <body> <div>模拟拖拽</div> <script> var oBox = document.getElementById('box'); drag(oBox); function drag(obj){ obj.onmousedown = function(ev){ // 鼠标按下 var ev = ev || event; // 获取鼠标离div得距离 var mouseBoxleft = ev.clientX - this.offsetLeft; var mouseBoxTop = ev.clientY - this.offsetTop; // IE浏览器,全局捕获 if(obj.setCapture){ obj.setCapture(); } document.onmousemove = function(ev){ // 鼠标按下左键并移动 var ev = ev || event; // 设置div移动时,它的位置 obj.style.left = ev.clientX - mouseBoxleft + 'px'; obj.style.top = ev.clientY - mouseBoxleft + 'px'; } document.onmouseup = function(){ // 鼠标左键抬起 document.onmousemove = document.onmouseup = null; //IE下,释放全局捕获 releaseCapture(); if ( obj.releaseCapture ) { obj.releaseCapture(); } } // 阻止默认行为 return false; } } </script> </body> </html>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wwfxxj.html