效果如下:
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> body{position:relative;} *{padding:0;margin:0;} .dialog{width:400px;height:400px;border:1px solid #ddd;position:fixed;top:100px;left:200px;} .dialog h2{height:40px;background:purple;cursor:move;} .mask{position:fixed;width:0;height:0;left:0;top:0;display:none;border: 3px solid #eee;box-shadow: 0px 0px 10px 5px rgba(0, 0, 0, 0.07);cursor:move;} </style> </head> <body> <div class="dialog" id="box"> <h2 id='digTit'></h2> </div> <div class="mask"></div> <script type="text/javascript"> var dragEle = document.getElementById('digTit') var box = document.getElementById('box') var x,y // 物体离上边,下边的距离 var moveBox = document.querySelector('.mask') // 移动的是这层 // 设置居中 var oldX = (document.documentElement.clientWidth-box.offsetWidth)/2 var oldY = (document.documentElement.clientHeight-box.offsetHeight)/2 box.style.left = oldX + 'px' box.style.top = oldY + 'px' moveBox.style.left = oldX + 'px' moveBox.style.top = oldY + 'px' moveBox.style.width = box.offsetWidth + 'px' moveBox.style.height = box.offsetHeight + 'px' digTit.addEventListener('mousedown', function (e) { moveBox.style.display = 'block' var beginX = e.clientX var beginY = e.clientY document.addEventListener('mousemove', move, false) document.addEventListener('mouseup', up, false) function move(e) { x = oldX + e.clientX - beginX y = oldY + e.clientY - beginY moveBox.style.left = x + 'px' moveBox.style.top = y + 'px' } function up(e) { box.style.left = x + 'px' box.style.top = y + 'px' oldX = x oldY = y moveBox.style.display = 'none' document.removeEventListener('mousemove', move, false) document.removeEventListener('mouseup', up, false) } }, false) </script> </body> </html>