把offsetY
改成pageY
就行了。
關于offsetY
的意思,規范是這么寫的:
The MouseEvent.offsetY read-only property provides the offset in the Y coordinate of the mouse pointer between that event and the padding edge of the target node.
關于pageY
的意思:
The MouseEvent.pageY read-only property returns the vertical coordinate of the event relative to the whole document.
你體會一下這兩者的區別,然后再想想為什么offsetY
不行。
最后,個人覺得你的js代碼寫的有點亂……我稍微改了改,你可以參考下:
$(document).ready(function(){ let axiL = 0,
doc = $(document),
b = $("#b"); //定義鼠標拖動時執行的函數
function move(event){ const top = parseInt(b.css("top")); let axiN = top + event.pageY - axiL;
axiN = (axiN < 0) ? 0: axiN;
axiN = (axiN > 170) ? 170: axiN;
b.css("top", axiN);
axiL = event.pageY;
}
b.on("mousedown", function() {
doc.on("mousemove", move);
axiL = event.pageY;
});
doc.on("mouseup", function() {
doc.off("mousemove", move);
});
});