1. 程式人生 > 其它 >JS實現登入框拖動功能

JS實現登入框拖動功能

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * 
{ margin: 0; padding: 0; } li { list-style: none; } body { background-color: rgb(175, 178, 175); } .btn { display: block; margin: 0 auto; width:
300px; height: 50px; cursor: pointer; background-color: rgb(48, 126, 248); border: 0; color: #fff; } .login { position: fixed; display: none; width: 500px; height: 300px; background-color
: #fff; box-shadow: 2px 2px 2px 5px #fff; left: 50%; top: 50%; border-radius: 10px; transform: translate(-50%, -50%); } .login h3 { text-align: center; font-weight: 500; margin-top: 10px; margin-left: 20px; } .login ul li { text-align: center; } .login ul li label { display: inline-block; min-width: 100px; } .login ul li input { height: 35px; width: 300px; margin-top: 20px; padding-left: 10px; border: 1px solid #ccc; } .login ul li button { margin-top: 30px; margin-left: 20px; width: 250px; height: 40px; background-color: #fff; border: 1px solid #ccc; font-weight: 600; outline: none; cursor: pointer; } .login span { position: absolute; font-size: 12px; width: 40px; height: 40px; top: -23px; right: -23px; border-radius: 50%; text-align: center; line-height: 40px; border: 1px solid #ccc; background-color: #fff; cursor: pointer; } .box { width: 100%; height: 100%; background-color: rgb(176, 179, 176); } </style> <script> window.addEventListener('load', function() { var btn = document.querySelector('.btn'); var login = document.getElementById('login'); var btn_close = document.getElementById('close'); var title = document.getElementById('title'); // 點選後彈出登入框 btn.addEventListener('click', function() { login.style.display = 'block'; }); // 點選關閉後隱藏登入彈框 btn_close.addEventListener('click', function() { login.style.display = 'none'; }); // 當我鼠按下登入框就可以實現拖動效果 title.addEventListener('mousedown', function(e) { this.style.cursor = 'move'; var x = e.pageX - login.offsetLeft; var y = e.pageY - login.offsetTop; document.addEventListener('mousemove', move); function move(e) { login.style.cursor = 'move'; login.style.left = e.pageX - x + 'px'; login.style.top = e.pageY - y + 'px'; } 當滑鼠鬆開時 login.addEventListener('mouseup', function() { document.removeEventListener('mousemove', move); }); }); }); </script> </head> <body> <button class="btn">點選彈出登入框</button> <div class="login" id="login"> <form action=""> <h3 id="title">登入會員</h3> <ul> <li><label for="uName">使用者名稱:</label> <input type="text" name="" placeholder="請輸入使用者名稱"> </li> <li> <label for="password">登入密碼:</label> <input type="password" name="" placeholder="請輸入密碼"> </li> <li><button type="submit">登入會員</button></li> </ul> </form> <span id="close">關閉</span> </div> </body> </html>