如何使用JavaScript将HTML图像移动到单击位置



我正试图将HTML图像(黑色标记(移动到屏幕上单击地图的位置。该地图有一个onclick功能,可以使标记可见并移动到用户单击的位置。然而,目前这只适用于我使用的屏幕大小,每当窗口大小发生变化时,每个轴上的图像都会偏离几百个像素。

目前,我将点击的坐标存储在一个数组中,并使用DOM style.left/top来更改位置,并使用这些坐标加上一组对我有效的像素,但不使用任何其他屏幕。我想要一种方法,让它移动到用户点击的任何地方,而不考虑页面的尺寸。

这是我目前做事的方式,坐标是包含相对坐标的数组:

document.getElementById('black-marker').style.visibility = 'visible';
document.getElementById('black-marker').style.left = coords[0]-20;
document.getElementById('black-marker').style.top = coords[1]+205;

单击红色框,黑色圆圈将移动到鼠标点。

我得到了红框的位置和鼠标的位置,并用它们来计算黑框的相对位置。

const blackMarker = document.getElementById('black-marker');
const parent = blackMarker.parentElement;
parent.addEventListener('click', e => {
const {
x,
y,
width,
height
} = parent.getBoundingClientRect();
blackMarker.style.left = `${(e.clientX - x) / width * 100}%`;
blackMarker.style.top = `${(e.clientY - y) / height * 100}%`;
});
body {
width: 100vw;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
div {
position: relative;
width: 150px;
height: 150px;
background-color: red;
}
span {
position: absolute;
transform: translate(-50%, -50%);
width: 25px;
border-radius: 50%;
height: 25px;
background-color: black;
}
<div>
<span id="black-marker"></span>
</div>

最新更新