本文介紹一款極度精簡的 JavaScript 拖曳層實作,完整支援 IE、Firefox、Opera、Safari 等主流瀏覽器。程式碼經過精心封裝,開發者只需複製貼上即可直接使用,進階開發者更可在此基礎上擴充更多功能,打造更強大的互動元件。
拖曳功能的核心在於滑鼠事件的三階段處理:mousedown 記錄初始座標、mousemove 即時更新元素位置、mouseup 釋放事件綁定。透過 clientX/clientY 取得滑鼠位置,配合 parseInt 解析元素當前 left/top 值,計算位移差值即可實現平滑拖曳。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS 拖曳層示範</title>
</head>
<body>
<div id="f" style="position: absolute; width: 216px; height: 138px; background-color: skyblue; font-size: 12px; top: 210px; left: 180px; z-index: 101; border: solid 1px blue;">
<div id="title" style="background-color: Blue; cursor: move; height: 20px; color: #fff; font-size: 12px; padding-top: 5px; padding-left: 10px;">層的標題</div>
層的內容
</div>
<script type="text/javascript">
var posX, posY;
var fdiv = document.getElementById("f");
document.getElementById("title").onmousedown = function(e) {
if (!e) e = window.event; // IE 相容
posX = e.clientX - parseInt(fdiv.style.left);
posY = e.clientY - parseInt(fdiv.style.top);
document.onmousemove = mousemove;
};
document.onmouseup = function() {
document.onmousemove = null;
};
function mousemove(ev) {
if (ev == null) ev = window.event; // IE 相容
fdiv.style.left = (ev.clientX - posX) + "px";
fdiv.style.top = (ev.clientY - posY) + "px";
}
</script>
</body>
</html>
e = e || window.event 統一處理 IE 與標準瀏覽器的事件物件差異。clientX - 元素左邊距 得到滑鼠相對元素的初始偏移,移動時以此為基準計算新位置。可進一步加入邊界限制、吸附對齊、拖曳代理、觸控裝置支援等功能,打造生產級的拖曳元件。