這個示例把兩個效果結合起來:拖動時元素變半透明,鬆手後恢復不透明。這個細節看似微小,卻能給用戶明確的「我正在操作」反饋,比單純能拖動要精緻不少。
#div2{
position:absolute;
width:400px; height:300px;
border:1px solid #333333;
background-color:#777788;
text-align:center;
line-height:400%;
font-size:13px;
left:80px; top:20px;
}
<script type="text/javascript">
var _move = false; // 移動標記
var _x, _y; // 鼠標離控件左上角的相對位置
$(document).ready(function(){
$("#div2").mousedown(function(e){
_move = true;
_x = e.pageX - parseInt($("#div2").css("left"));
_y = e.pageY - parseInt($("#div2").css("top"));
$("#div2").fadeTo(20, 0.25); // 點擊後開始拖動並半透明顯示
});
$(document).mousemove(function(e){
if (_move) {
var x = e.pageX - _x; // 根據鼠標位置計算新的 left
var y = e.pageY - _y;
$("#div2").css({ top: y, left: x });
}
}).mouseup(function(){
_move = false;
$("#div2").fadeTo("fast", 1); // 鬆開後停止移動並恢復不透明
});
});
</script>
偏移量記錄是拖拽的關鍵。滑鼠按下時,先算出鼠標位置與元素左上角的差值 _x、_y。之後移動時用當前鼠標位置減去這個差值,元素就會始終保持「按下時的那個位置被鼠標抓住」的相對關係,不會出現跳動。
為什麼事件綁在 document 上。mousedown 綁在元素上(拖拽只能從元素啟動),但 mousemove 與 mouseup 必須綁在 document 上——否則鼠標一旦移出元素範圍就再也收不到事件,拖拽會中途卡住。
fadeTo 的兩個參數。第一個是時長(可傳 "fast"/"slow" 或毫秒數),第二個是目標透明度。按下時 20 毫秒過渡到 0.25,鬆手時快速回到 1。
<html>
<head>
<title>jQuery實現DIV層淡入淡出的拖動效果</title>
<style type="text/css">
#div2{
position:absolute;
width:400px; height:300px;
border:1px solid #333333;
background-color:#777788;
text-align:center;
line-height:400%;
font-size:13px;
left:80px; top:20px;
}
</style>
<script type="text/javascript" src="/images/jquery.js"></script>
<script type="text/javascript">
var _move = false;
var _x, _y;
$(document).ready(function(){
$("#div2").click(function(){
// 點擊(鬆開後觸發)
}).mousedown(function(e){
_move = true;
_x = e.pageX - parseInt($("#div2").css("left"));
_y = e.pageY - parseInt($("#div2").css("top"));
$("#div2").fadeTo(20, 0.25);
});
$(document).mousemove(function(e){
if (_move) {
var x = e.pageX - _x;
var y = e.pageY - _y;
$("#div2").css({ top: y, left: x });
}
}).mouseup(function(){
_move = false;
$("#div2").fadeTo("fast", 1);
});
});
</script>
</head>
<body>
<h4>看不到效果,請刷新一下本頁面。</h4>
<div id="div2">
支持拖拽<br>
如果不能拖動,請刷新本頁面
</div>
</body>
</html>
· 缺少邊界約束。目前可以把元素拖到屏幕外再也拉不回來。加一段 Math.max/min 夾取值即可:
var maxL = $(window).width() - $("#div2").width();
var maxT = $(window).height() - $("#div2").height();
x = Math.max(0, Math.min(x, maxL));
y = Math.max(0, Math.min(y, maxT));
· 用 parseInt 解析 css("left") 有隱患。若元素初始未設 left,jQuery 返回的可能是 "auto",parseInt("auto") 得到 NaN,後續計算全部失效。建議改用 $("#div2").offset().left,它始終返回數值。
· 拖拽中應防止選中文本。在 mousedown 回調裡加 return false; 或調用 e.preventDefault()。
· 只監聽了 mouseup,缺少 mouseleave 場景。鼠標在窗口外鬆開時,_move 會一直停在 true,導致元素黏著鼠標移動。補上 $(window).on("blur mouseleave", ...) 更穩妥。
· 用 left/top 改位置會觸發重排。改用 transform: translate() 由合成層處理,拖動會更順滑,尤其在元素內容複雜時差異明顯。
· 若不需要 jQuery,原生實現也很短。用 Pointer Events 並配合 setPointerCapture,能同時支援鼠標與觸屏:
const box = document.getElementById('div2');
let dragging = false, offsetX = 0, offsetY = 0;
box.addEventListener('pointerdown', (e) => {
dragging = true;
offsetX = e.clientX - box.offsetLeft;
offsetY = e.clientY - box.offsetTop;
box.setPointerCapture(e.pointerId);
box.style.opacity = '0.25';
e.preventDefault();
});
box.addEventListener('pointermove', (e) => {
if (!dragging) return;
const maxL = window.innerWidth - box.offsetWidth;
const maxT = window.innerHeight - box.offsetHeight;
const x = Math.max(0, Math.min(e.clientX - offsetX, maxL));
const y = Math.max(0, Math.min(e.clientY - offsetY, maxT));
box.style.transform = `translate(${x - box.offsetLeft}px, ${y - box.offsetTop}px)`;
});
function endDrag(e) {
if (!dragging) return;
dragging = false;
box.style.opacity = '1';
}
box.addEventListener('pointerup', endDrag);
box.addEventListener('pointercancel', endDrag);
原示例用不到二十行就實現了「拖拽 + 透明度反饋」,作為 jQuery 事件與樣式操作的練習非常合適;補上邊界與事件清理之後,就是一個可以直接用的浮動層基礎。