首页 > 解决方案 > 如何在 javascript 中基于鼠标单击重叠 2 个图像?

问题描述

期望的行为是能够在网格中单击,并且覆盖的图像将保持在正确的正方形中。但是,在调整浏览器窗口大小时,定位会变得混乱(参见下面的链接)。

问题演示链接:https ://www.youtube.com/watch?v=4fbPlQLvHLs

function onClick(e) {
    let xPos = e.clientX;
    let yPos = e.clientY;

    var newImg = document.createElement("img");
    newImg.src = 'https://www.pngmart.com/files/4/Circle-PNG-File.png';
    newImg.style.position = "absolute";
    newImg.style.left = xPos + "px";
    newImg.style.top = yPos + "px";
    newImg.style.width = "35px";
    document.getElementById("wrapper").appendChild(newImg);
<div class="wrapper" id="wrapper">
    <img id="my-image" src="https://www.guineapigcagesstore.com/resize/Shared/Images/Product/Standard-Grid/standard-grid.jpg?bw=1000&w=1000&bh=1000&h=1000" 
    alt="img" width="300px" position="relative" ></img>
</div>

包装样式:

.wrapper {
    text-align: center;
}

标签: javascripthtmlcssimageoverlay

解决方案


推荐阅读