另一種常見做法是透過多個變數記錄滑鼠按下時的位置與元素位置,再在 mousemove 中計算位移。這種方式適合需要與既有事件系統整合的浮動視窗。
function M_Keydown(e) {
IsKeydown = 1;
defaultx = e.pageX;
defaulty = e.pageY;
objx = $(".Pop_Layer")[0].offsetLeft;
objy = $(".Pop_Layer")[0].offsetTop;
}
function M_Move(ee) {
if (IsKeydown == 1) {
$(".Pop_Layer").css("left", objx + ee.pageX - defaultx);
$(".Pop_Layer").css("top", objy + ee.pageY - defaulty);
}
}
搭配 Pop_Head 作為拖曳把手,就能讓使用者只從標題列拖動視窗,避免誤觸內容區。