彈出層幾乎每個網站都會用到。下面這份範例不依賴任何套件,包含遮罩、置中顯示與標題列拖曳三個部分,可以直接跑起來。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>可拖曳的彈出層</title>
<style>
html, body { height: 100%; overflow: hidden; }
body, div, h2 { margin: 0; padding: 0; }
body { font: 12px/1.5 Tahoma; }
center { padding-top: 10px; }
button { cursor: pointer; }
#overlay {
position: absolute; top: 0; left: 0;
width: 100%; height: 100%;
background: #000; opacity: 0.5; filter: alpha(opacity=50);
display: none;
}
#win {
position: absolute; top: 50%; left: 50%;
width: 400px; height: 200px;
background: #fff; border: 4px solid #f90;
margin: -102px 0 0 -202px; /* 負 margin 實現置中 */
display: none;
}
h2 {
font-size: 12px; height: 18px; text-align: right;
background: #FC0; border-bottom: 3px solid #f90;
padding: 5px; cursor: move; /* 標題列作為拖曳把手 */
}
h2 span {
color: #f90; cursor: pointer;
background: #fff; border: 1px solid #f90; padding: 0 2px;
}
</style>
</head>
<body>
<div id="overlay"></div>
<div id="win">
<h2 id="bar">拖曳我 <span id="close">×</span></h2>
<p style="padding:10px;">這裡放彈出層的內容。</p>
</div>
<center><button id="open">彈出層</button></center>
<script>
var win = document.getElementById('win'),
overlay = document.getElementById('overlay'),
bar = document.getElementById('bar');
// 顯示 / 隱藏
document.getElementById('open').onclick = function () {
win.style.display = overlay.style.display = 'block';
};
document.getElementById('close').onclick = function () {
win.style.display = overlay.style.display = 'none';
};
overlay.onclick = function () { // 點遮罩也能關閉
win.style.display = overlay.style.display = 'none';
};
// 拖曳
var dragging = false, offsetX = 0, offsetY = 0;
bar.onmousedown = function (e) {
e = e || window.event;
dragging = true;
offsetX = e.clientX - win.offsetLeft;
offsetY = e.clientY - win.offsetTop;
return false; // 避免選取到文字
};
document.onmousemove = function (e) {
e = e || window.event;
if (!dragging) return;
win.style.left = (e.clientX - offsetX) + 'px';
win.style.top = (e.clientY - offsetY) + 'px';
win.style.margin = '0'; // 拖曳後取消置中所用的負 margin
};
document.onmouseup = function () { dragging = false; };
</script>
</body>
</html>top/left: 50% 搭配負 margin 把元素拉回中心,比計算視窗寬高更省事若要支援行動裝置,把 mousedown / mousemove / mouseup 換成 touchstart / touchmove / touchend,並改用 e.touches[0].clientX 取值即可。