如何将元素放入div并检索相对于div元素的坐标?



我有一个id="drag"的div元素,如果一个id='drag'的div元素被拖放到一个id="drop"的div元素上,它将显示相对于id="drop"的div元素的坐标值。. 我已经设法检索了相对于div id="drop"的坐标,但是当页面滚动时,Y值也发生了变化。如何解决这个问题,以便当页面滚动的Y值仍然相对于div与id='drop'?下面是我的代码

`<!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) {
var rect = e.target.getBoundingClientRect();
const coordinates = [
Math.round(e.pageX - rect.left),
Math.round(e.pageY - rect.top),
];
console.log(coordinates[0]);
console.log(coordinates[1]);
},
});
});
</script>
</html>`

至少从这里开始,它不会改变。

你可以这样检查:

$(function () {
var coordinates;
$("#drag").draggable();
$("#drop").droppable({
accept: "#drag",
drop: function (e) {
var rect = e.target.getBoundingClientRect();
coordinates = [
Math.round(e.pageX - rect.left),
Math.round(e.pageY - rect.top),
];
setInterval(() => {
console.log(coordinates[0]);
console.log(coordinates[1]);
}, 500);
},
});
});

最新更新