关于js实现最简单的拖拽
http://www.cnblogs.com/hongru/archive/2010/09/22/1833030.html
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> *{margin:0;padding:0} body{font:12px/1.5 arial} div{position:absolute;width:300px;height:200px;border:5px solid #ddd;background:#fff} h2{background:#f4f4f4} </style> </head> <body> <div> <h2>对话框</h2> </div> <script> var getStyle = function(o, key) {// o object // currentStyle only for ie5.0+ return o.currentStyle ? o.currentStyle[key] : document.defaultView.getComputedStyle(o, null)[key]; }; var drag = function(bar, target) { var params = { startLeft: 0, startTop: 0, _X: 0, _Y: 0, isDarg: false }; // 刷新页面时,获取所在位置 if (getStyle(target, 'left') != 'auto') { params.startLeft = getStyle(target, 'left'); } if (getStyle(target, 'top') != 'auto') { params.startTop = getStyle(target, 'top'); } // 鼠标按下时,获取鼠标位置 bar.onmousedown = function(e) { e = e ? e : window.event; params.isDarg = true; params._X = e.clientX; params._Y = e.clientY; }; // 鼠标移动时,重新设定位置 document.onmousemove = function(e) { var e = e ? e : window.event; if (params.isDarg) { var curX = e.clientX, curY = e.clientY, desL = curX - params._X + parseInt(params.startLeft),// parseInt('22px') 返回由字符串转换得到的整数 desT = curY - params._Y + parseInt(params.startTop); target.style['left'] = desL >= 0 ? desL + 'px' : 0; target.style['top'] = desT >= 0 ? desT + 'px' : 0; } }; // 鼠标释放时,获取所在位置 document.onmouseup = function() { params.isDarg = false; if (getStyle(target, 'left') != 'auto') { params.startLeft = getStyle(target, 'left'); } if (getStyle(target, 'top') != 'auto') { params.startTop = getStyle(target, 'top'); } }; }; //drag(document.getElementsByTagName('div')[0], document.getElementsByTagName('div')[0]); drag(document.getElementsByTagName('h2')[0], document.getElementsByTagName('div')[0]); </script> </body> </html>