我目前正在尝试d-i-y拼贴游戏,用户可以单击图像并将其拖动到所需位置。该代码可以正常工作,除了在加载时,所有图像都在左上角缩小。它们彼此重叠,并将它们隐藏在它们下面。
我不知道为什么随机位置生成无法正常工作。图像在div中,作为一个初学者,我不知道当前是否还有另一种方法。 Math.random()是否可能?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
let currentlyDragging;
let drawing = false;;
let offset_x;
let offset_y;
let puzzle;
$(window).load(function () {
$(".draggable").click(startDragging);
$(".draggable").mousemove(whileDragging);
$("#puzzle").mousemove(whileDragging);
puzzle = document.getElementById("puzzle");
});
function startDragging(e) {
if (!drawing) {
drawing = true;
currentlyDragging = $(this);
if (offset_x == null && offset_y == null) {
var current_origin_y;
var current_origin_x;
var current_origin_y_string = currentlyDragging.context.style['margin-top'];
if (current_origin_y_string === "") {
current_origin_y = 0;
} else {
current_origin_y = parseInt(current_origin_y_string.split("px")[0]);
}
var current_origin_x_string = currentlyDragging.context.style['margin-left'];
if (current_origin_x_string === "") {
current_origin_x = 0;
} else {
current_origin_x = parseInt(current_origin_x_string.split("px")[0]);
}
offset_x = current_origin_x - e.pageX;
offset_y = current_origin_y - e.pageY;
}
} else {
drawing = false;
currentlyDragging = null;
offset_x = null;
offset_y = null;
}
}
function whileDragging(e) {
if (currentlyDragging == null) {
return false;
}
currentlyDragging.css({
"margin-top": Math.min(Math.max(e.pageY + offset_y, 0), puzzle.clientHeight - currentlyDragging.context.height) + "px",
"margin-left": Math.min(Math.max(e.pageX + offset_x, 0), puzzle.clientWidth - currentlyDragging.context.width) + "px"
});
}
</script>
<style>
.draggable {
position: absolute;
cursor: pointer;
user-select: none;
}
</style>
<div id="puzzle" scroll="no" style="height: 100%; overflow: hidden; border: 5px solid yellow;">
<img class=draggable src="https://avatars3.githubusercontent.com/u/9167554?s=460&v=4" width=50 height=50 />
<img class=draggable src="https://avatars3.githubusercontent.com/u/9167554?s=460&v=4" width=50 height=50 />
<img class=draggable src="https://avatars3.githubusercontent.com/u/9167554?s=460&v=4" width=50 height=50 />
<img class=draggable src="https://avatars3.githubusercontent.com/u/9167554?s=460&v=4" width=50 height=50 />
<img class=draggable src="https://avatars3.githubusercontent.com/u/9167554?s=460&v=4" width=50 height=50 />
</div>
</body>