原生 JavaScript 的提示對話框外觀單調,若改用自訂彈窗,就能在樣式上完全掌控。本文分享一個點擊按鈕彈出登入視窗、且視窗可自由拖拽的完整實作。
包含觸發按鈕與彈窗本體,彈窗內有標題列、帳號密碼輸入、登入按鈕與第三方登入等區塊:
<button id="show" class="alter">彈窗</button>
<div class="box">
<div class="box_content">
<div class="title"><h3>登錄通行證</h3><h2 id="close">×</h2></div>
<div class="content"> ...帳號、密碼、登入按鈕... </div>
</div>
</div>
.box 為全屏遮罩,.box_content 為置中彈窗,標題列 .title 設 cursor:move 提示可拖拽:
.box{ width:100%; height:100%; position:fixed; top:0; left:0; z-index:100000; display:none;}
.box_content{ height:420px; width:350px; background:white; position:fixed; top:0; left:0; }
.title:hover{cursor: move;}
以 BoxInit 物件封裝,初始化時取得各控制項與視窗寬高,綁定顯示、關閉、拖拽等事件。顯示時先展開遮罩,再把彈窗動畫移到視窗正中央:
showBtn:function(){
var self=this;
self.box.animate({"width":self.wWidth,"height":self.wHeight},function(){
self.boxContent.animate({ "left":(self.wWidth-self.boxContent.width())/2 },function(){
$(this).animate({"top":(self.wHeight-self.boxContent.height())/2});
});
});
}
拖拽則透過 mousedown 記錄滑鼠相對偏移量,於 mousemove 時計算新座標並限制在視窗範圍內,避免拖出畫面。此外還實作了「提示文字點擊隱藏、輸入框失焦時顯示」的貼心互動。整個功能完整且流暢,是製作登入彈窗很好的參考範本。