拖拽視窗案例
阿新 • • 發佈:2021-08-16
<!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; } .nav { height: 30px; background: #036663; border-bottom: 1px solid #369; line-height: 30px; padding-left: 30px; } .nav a { color: #fff; text-align: center; font-size: 14px; text-decoration: none; } .d-box { width: 400px; height: 300px; border: 5px solid #eee; box-shadow: 2px 2px 2px 2px #666; position: absolute; top: 40%; left: 40%; background-color: white; /* 不讓文字被選中 */ -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } .hd { width: 100%; height: 25px; background-color: #7c9299; border-bottom: 1px solid #369; line-height: 25px; color: white; cursor: move; } #box_close { float: right; cursor: pointer; } </style> </head> <body> <div class="nav"> <a href="javascript:;" id="register">註冊資訊</a> </div> <div class="d-box" id="d_box"> <div class="hd" id="drop">註冊資訊 (可以拖拽) <span id="box_close">【關閉】</span> </div> <div class="bd"></div> </div> <script> var drop = document.getElementById("drop"); var box = document.getElementById("d_box"); var box_close = document.getElementById("box_close"); drop.onmousedown = function(e){ e = e || window.event; //記憶滑鼠按下時滑鼠在父盒子內部的間距 var l = e.pageX - box.offsetLeft; var t = e.pageY - box.offsetTop; drop.onmousemove = function(e){ e = e || window.event; var nowleft = e.pageX - l; var nowtop = e.pageY - t; //賦值給box的樣式屬性 box.style.left = nowleft+"px"; box.style.top = nowtop+"px"; } }; //滑鼠彈起事件 drop.onmouseup = function(){ drop.onmousemove = null; } //點選關閉彈窗 box_close.onclick = function(){ box.style.display = "none"; } </script> </body> </html>