效果:
源码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>速表拖拽效果实现</title> <style> *{ margin: 0; padding: 0; } .toolbar{ height: 30px; text-align: left; padding-left: 20px; background: #036663; line-height: 30px; color: #fff; } .regist{ width: 410px; height: 310px; margin: 200px auto; border:5px solid #eee; box-shadow:2px 2px 2px 2px #666; } .rt{ height: 26px; background: #7C9299; color: #fff; line-height: 26px; cursor: move; } .rts{ float: right; } </style> </head> <body> <div class="toolbar">注册信息</div> <div class="regist" id="regist"> <div class="rt" id="rt"> <span>注册信息(可以拖拽)</span> <span class="rts">【关闭】</span> </div> </div> <script> var regist = document.getElementById("regist"); var rt = document.getElementById("rt"); var x = 0,y = 0; rt.onmousedown = function(event){ var event = event || window.event; x = event.clientX - regist.offsetLeft; y = event.clientY - regist.offsetTop + 30;//加三十是因为顶部工具条占了30,而regist的没有父亲,所以他是以body为定位点,所以。。。 document.onmousemove = function(event){ var event = event || window.event; regist.style.marginLeft = event.clientX - x +"px"; regist.style.marginTop = event.clientY - y +"px"; window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty(); } document.onmouseup = function(){ document.onmousemove = null; } } </script> </body> </html>