如何获取拖拽元素相对div的坐标并解决滚动时Y值偏移问题
解决拖拽时页面滚动导致相对坐标Y值偏移的问题
问题根源是坐标基准不统一:你用e.pageY(基于文档顶部的坐标)减去getBoundingClientRect().top(基于视口顶部的坐标),页面滚动时drop元素的视口位置会变化,导致计算出的Y值跟着偏移。
直接用jQuery的offset()方法就能解决,它返回元素相对于文档左上角的坐标,和e.pageX/e.pageY的基准完全一致:
修改后的完整代码如下:
<!DOCTYPE html> <html lang="en"> <head> <title>jQuery UI Droppable</title> </head> <body style="height: 200vh"> <div id="drop" style=" width: 600px; height: 600px; background-color: brown; margin: 0 auto; " ></div> <div id="drag" style="background-color: blue; width: 100px; height: 100px" ></div> </body> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(function () { $("#drag").draggable(); $("#drop").droppable({ accept: "#drag", drop: function (e) { // 获取drop元素相对于文档的坐标 const dropOffset = $(this).offset(); const coordinates = [ Math.round(e.pageX - dropOffset.left), Math.round(e.pageY - dropOffset.top), ]; console.log("X坐标:", coordinates[0]); console.log("Y坐标:", coordinates[1]); }, }); }); </script> </html>
关键说明
$(this).offset()获取的left和top值,始终以文档左上角为参考点,和e.pageX/e.pageY的参考系完全匹配,不管页面怎么滚动,两者的差值都是拖拽点相对于drop元素的准确坐标。- 替换掉原来的
getBoundingClientRect(),就彻底消除了滚动带来的Y值偏移问题。
内容的提问来源于stack exchange,提问作者Gung Andre
相关产品推荐
相关产品推荐

