標題欄可拖動移動浮層,右上角關閉按鈕帶濾鏡淡出動畫,純原生 JS 無依賴。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>可拖動關閉浮層</title>
<style>
#floatLayer {
position: absolute; top: 60px; left: 200px;
width: 360px; height: 250px; background: #ffff00;
border: 1px solid #ccc; box-shadow: 2px 2px 8px rgba(0,0,0,.2);
font-family: sans-serif; user-select: none;
}
#titleBar {
background: #30608f; color: #fff; padding: 6px 10px;
font-size: 14px; cursor: move;
}
#closeBtn {
position: absolute; right: 8px; top: 6px; width: 16px; height: 16px;
background: url('data:image/svg+xml,') center/contain no-repeat;
cursor: pointer; opacity: 0.7; transition: opacity .2s;
}
#closeBtn:hover { opacity: 1; }
.content { padding: 15px; }
</style>
</head>
<body>
<div id="floatLayer">
<div id="titleBar">可拖動浮層標題</div>
<div id="closeBtn" title="關閉"></div>
<div class="content">這裡放置任意內容...</div>
</div>
<script>
(function() {
var layer = document.getElementById('floatLayer');
var titleBar = document.getElementById('titleBar');
var closeBtn = document.getElementById('closeBtn');
var isDragging = false, offsetX, offsetY;
// 拖動邏輯
titleBar.addEventListener('mousedown', function(e) {
isDragging = true;
offsetX = e.clientX - layer.offsetLeft;
offsetY = e.clientY - layer.offsetTop;
document.body.style.cursor = 'move';
e.preventDefault(); // 防止選中文本
});
document.addEventListener('mousemove', function(e) {
if (!isDragging) return;
layer.style.left = (e.clientX - offsetX) + 'px';
layer.style.top = (e.clientY - offsetY) + 'px';
});
document.addEventListener('mouseup', function() {
isDragging = false;
document.body.style.cursor = '';
});
// 關閉動畫
closeBtn.addEventListener('click', function() {
layer.style.transition = 'opacity 0.3s, transform 0.3s';
layer.style.opacity = '0';
layer.style.transform = 'scale(0.9)';
setTimeout(function() { layer.style.display = 'none'; }, 300);
});
})();
</script>
</body>
</html>
clientX - offsetLeft 得到鼠標相對層左上角的偏移,移動時用 clientX - offsetX 還原層位置。mousedown 在標題欄,mousemove/mouseup 在 document 上,確保鼠標移出標題欄仍能拖動。e.preventDefault() + CSS user-select:none。transition 配合 opacity/transform,動畫結束後 display:none 釋放佈局空間。left < 0、top < 0、right > viewportWidth、bottom > viewportHeight。div.overlay 覆蓋全頁,z-index 略低於浮層。touchstart/touchmove/touchend 事件處理移動端拖動。DraggableLayer 類,支持 new DraggableLayer('#id') 實例化多個。原生 JS 實現拖動浮層僅需 30 行核心代碼,理解「事件分離綁定、座標換算、動畫過渡」三大要點即可舉一反三。現代項目建議優先用 CSS transition 替代濾鏡,並補充觸摸事件實現全端適配。