JavaScript實現拖拽盒子效果
阿新 • • 發佈:2020-02-07
本文例項為大家分享了JavaScript實現拖拽盒子效果的具體程式碼,供大家參考,具體內容如下
實現效果:
1.單擊關閉,關閉盒子
2.點選左上方‘點選註冊',開啟盒子
3.滑鼠放在盒子上方藍色區域顯示十字
4.點選滑鼠不鬆開就可移動盒子
5.鬆開滑鼠圖片暫停
實現步驟:
1.在頁面最上方設定一個盒子,裡面有一個超連結,超連結裡面設定href="javascript:void(0);",再點選時不開啟網頁。
2.再設定一個可以拖拽的盒子,盒子巢狀一個藍色盒子為的最上方的藍色區域,藍色盒子裡面兩個span標籤,裡面寫‘關閉'和‘可拖拽'。
3.給‘關閉'的盒子註冊點選事件,點選後,拖拽盒子樣式為none,(不顯示)
4.給上方藍色盒子設定onmousedown(滑鼠點選事件),同時獲取滑鼠點選位置
離拖拽盒子的距離,為mouseLeft和mouseTop
5.給頁面(document)設定onmousemove事件讓滑鼠的位置分別減去mouseLeft和mouseTop,得到盒子左上角隨滑鼠移動的座標,再將座標賦值給拖拽盒子
6.最後設定onmouseup事件,滑鼠鬆開時頁面不移動。即document.onmousemove =null
實現細節:
1.讓拖拽盒子居中顯示:top:50%; left: 50%;
margin-left :-155px; margin-top:-155px;
所以設定-155px, margin-top:-(盒子高度的一半),和寬度同理)
2.var evt = event || window.event;相容性寫法。
程式碼:
<!DOCTYPE html> <html> <head> <title>拖拽盒子</title> <style type="text/css"> *{ margin:0px; padding:0px; } .dropBox{ width:300px; height:300px; top:50%; left:50%; margin-left: -155px; margin-top: -155px; display: block; border: 5px solid #aaa; position: absolute; } .nav{ width: 100%; height:30px; background-color: blue; opacity: 0.6; } .nav a{ font-size:15px; color:white; } .dropBox .box{ width:300px; height:30px; position: absolute; left:0px; top:0px; background-color: darkblue; opacity: 0.8; cursor:move; } .close{ float: right; color:white; font-size: 15px; cursor: pointer; } .move{ color:white; font-size: 15px; } </style> <script type="text/javascript"> function $(id){ return document.getElementById(id); } window.onload = function(){ var register = $('register'); var dropBox = $('dropDiv'); var box = $('box'); var box2 = $('box2'); box2.onclick = function(){ dropBox.style.display = 'none'; } register.onclick = function(){ dropBox.style.display = 'block'; } box.onmousedown = function(event){ var evt = event || window.event; var mouseLeft = evt.clientX - dropBox.offsetLeft; var mouseTop = evt.clientY - dropBox.offsetTop; document.onmousemove = function(event){ var evt = event || window.event; var x = evt.clientX - mouseLeft; var y = evt.clientY - mouseTop; dropBox.style.left = x + 155 + 'px'; dropBox.style.top = y + 155 + 'px'; } document.onmouseup = function (){ document.onmousemove = null; } } } </script> </head> <body> <div class="nav"> <a href="javascript:void(0);" id="register">點選註冊</a> </div> <div class="dropBox" id="dropDiv"> <div class="box" id="box"> <span class="move">註冊資訊(可以拖拽)</span> <span class="close" id="box2">【關閉】</span> </div> </div> </body> </html>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。