首页 > 解决方案 > 当我使用拖放时,拖动对象部署在 img 内部而不是 div

问题描述

我正在用javascript制作游戏,游戏包括沿棋盘拖放一些项目。

问题是有些<div>里面有物品(一个<img>),当我放下另一个时,掉落的物品会进入<img>里面<div>

这是我在下降之前所拥有的:

<div class="casa" id="39" ondrop="drop(event, this)" ondragover="allowDrop(event, this)">
    <img class="esgoto" id="esgoto39" src="./assets/esgoto.png" width="49" height="49" z-index="-1">
</div>

这是我drop后得到的:

<div class="casa" id="39" ondrop="drop(event, this)" ondragover="allowDrop(event, this)">
    <img class="esgoto" id="esgoto39" src="./assets/esgoto.png" width="49" height="49" z-index="-1">
        <img class="plr" id="drag8" src="./assets/8.png" width="35" height="35" z-index="10" draggable="true" ondragstart="drag(event, this)">
    </img>
</div>

这是我的 js 代码:

    function drop(ev, nariz) {
        ev.preventDefault();
        var data = ev.dataTransfer.getData("text");
        ev.target.appendChild(document.getElementById(data));

        let x = document.getElementById(nariz.id).children[0];
        let sinal = x.id;

        //other thing inside, each img.class have a specific action

}

这就是我要的:

<div class="casa" id="39" ondrop="drop(event, this)" ondragover="allowDrop(event, this)">
    <img class="esgoto" id="esgoto39" src="./assets/esgoto.png" width="49" height="49" z-index="-1">
    <img class="plr" id="drag8" src="./assets/8.png" width="35" height="35" z-index="10" draggable="true" ondragstart="drag(event, this)">
</div>

有人知道怎么做吗?PS:我避免使用所有框架和库。如果可能的话,我想做这个“香草”。

标签: javascripthtmlcss

解决方案


推荐阅读