拖拽效果
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>拖拽效果</title> <style> div{200px;height: 200px;background: cyan;position: absolute;} </style> <script> window.onload = function(){ var oDiv = document.getElementById('div1'); //鼠标按下 oDiv.onmousedown = function(ev){ var e = ev || window.event; //在鼠标按下是计算坐标 //offsetX或Y是鼠标相对于移动物体左上角的坐标 var offsetX = e.clientX - oDiv.offsetLeft; var offsetY = e.clientY - oDiv.offsetTop; //鼠标移动效果 document.onmousemove = function(ev){ var e = ev || window.event; oDiv.style.left = e.clientX - offsetX +'px'; oDiv.style.top = e.clientY - offsetY +'px'; } } //鼠标抬起 document.onmouseup = function(){ document.onmousemove = null; } } </script> </head> <body> <div id="div1"></div> </body> </html>
浏览器效果:
把上面的拖拽效果封装成函数:
代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>拖拽效果</title> <style> div{200px;height: 200px;background: cyan;position: absolute;} </style> <script> window.onload = function(){ var oDiv = document.getElementById('div1'); drag(oDiv); } /*------------封装拖拽函数------------*/ function drag(node){ ////offsetX或Y用于存取鼠标相对于移动物体左上角的坐标 var offsetX = 0; var offsetY = 0; //鼠标按下 node.onmousedown = function(ev){ var e = ev || window.event; //在鼠标按下是计算坐标 //offsetX或Y是鼠标相对于移动物体左上角的坐标 offsetX = e.clientX - this.offsetLeft; offsetY = e.clientY - this.offsetTop; //鼠标移动效果 document.onmousemove = function(ev){ var e = ev || window.event; node.style.left = e.clientX - offsetX +'px'; node.style.top = e.clientY - offsetY +'px'; } } //鼠标抬起 document.onmouseup = function(){ document.onmousemove = null; } } /*------------封装拖拽函数end------------*/ </script> </head> <body> <div id="div1"></div> </body> </html>
浏览器效果与上面相同;
把封装好的函数(如下)说明:
//形参node为元素节点 //调用格式为 drag(元素节点);
/*------------封装拖拽函数------------*/ //形参node为元素节点 //调用格式为 drag(元素节点); function drag(node){ ////offsetX或Y用于存取鼠标相对于移动物体左上角的坐标 var offsetX = 0; var offsetY = 0; //鼠标按下 node.onmousedown = function(ev){ var e = ev || window.event; //在鼠标按下是计算坐标 //offsetX或Y是鼠标相对于移动物体左上角的坐标 offsetX = e.clientX - this.offsetLeft; offsetY = e.clientY - this.offsetTop; //鼠标移动效果 document.onmousemove = function(ev){ var e = ev || window.event; node.style.left = e.clientX - offsetX +'px'; node.style.top = e.clientY - offsetY +'px'; } } //鼠标抬起 document.onmouseup = function(){ //主动调用鼠标移动事件对象函数(方法) document.onmousemove = null; } } /*------------封装拖拽函数end------------*/