1. 程式人生 > >js 滑鼠拖拽效果實現

js 滑鼠拖拽效果實現

 效果:

原始碼:

<!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>