fadeTo 0.25),釋放恢復不透明。<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery 拖曳淡入淡出 Demo</title>
<style>
#draggable {
position: absolute; left: 80px; top: 20px;
width: 400px; height: 300px;
border: 1px solid #333; background: #777788;
color: #fff; font-size: 14px; line-height: 300px;
text-align: center; user-select: none; cursor: move;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<h4>點擊標題區拖曳移動,釋放恢復不透明</h4>
<div id="draggable">可拖曳的浮動層</div>
<script>
$(function() {
const $el = $('#draggable');
let moving = false, offsetX, offsetY;
$el.on('mousedown', function(e) {
moving = true;
offsetX = e.pageX - $el.offset().left;
offsetY = e.pageY - $el.offset().top;
$el.fadeTo(20, 0.25); // 按下即半透明
});
$(document).on('mousemove', function(e) {
if (!moving) return;
$el.offset({ left: e.pageX - offsetX, top: e.pageY - offsetY });
}).on('mouseup', function() {
moving = false;
$el.fadeTo('fast', 1); // 釋放恢復
});
});
</script>
</body>
</html>
e.pageX - $el.offset().left 計算滑鼠相對元素左上角偏移,移動時用同樣偏移還原位置,避免元素「跳躍」。document 上處理 mousemove/mouseup,確保滑鼠移出元素外仍能繼續拖曳。fadeTo(duration, opacity) 同時處理動畫與透明度,簡潔好用。HTML Drag and Drop API 亦可實現無依賴版本,但需處理 dragstart/dragover/drop 細節。touchstart/move/end,或使用 Hammer.js 統一指標事件。利用 jQuery 事件系統與 offset()/fadeTo(),不到 30 行即可實作帶視覺反饋的拖曳浮動層,適合快速原型與輕量專案。