gpt4 book ai didi

javascript - 尝试只允许 1 张图像放入 div

转载 作者:行者123 更新时间:2023-11-28 06:01:54 26 4
gpt4 key购买 nike

您好,这几天我一直在尝试寻找一种方法,但一直没有成功。我有四个图像和四个 div 可以将它们放入。困难的部分是我只希望用户能够将每个图像仅放入相应的 div,而不能将它们放入多个位置。这样,只有第一张图片可以放入第一个框中,第二张可以放入第二张,依此类推。我不知道任何 jQuery,并且强烈希望尽可能简单地使用 javascript。谢谢!!

HTML:

<div class="inventory">
<p id="inventory">Inventory
<div class= "tooltip">
<img id="normalChest" ondragstart="drag(event)" src="chest.png" height = "25" width = "25" draggable = "true" ondrop="drop(event)" ondragover="allowDrop(event)" >
<span class= "tooltiptextnormal">Normal Chest</span>
</div>
<div class= "tooltip">
<img id="uncommonChest" ondragstart="drag(event)" src="SilverChest.png" height = "25" width = "25" draggable = "true" >
<span class= "tooltiptextuncommon">Uncommon Chest</span>
</div>
<div class= "tooltip">
<img id="rareChest" ondragstart="drag(event)" src="PlatinumChest.png" height = "25" width = "25" draggable = "true" >
<span class= "tooltiptextrare">Rare Chest</span>
</div>
<div class= "tooltip">
<img id="exoticChest" ondragstart="drag(event)" src="GoldChest.png" height = "25" width = "25" draggable = "true" >
<span class= "tooltiptextexotic">Exotic Chest</span>
</div>
</p>
<script src="game.js">
document.getElementById("inventory").innerHTML = inventory;
</script>

</div>


<div class="chestOpenerCommon" id="div1" ondragover="allowDropCommon(event)">
<h4>Open your Common chests here!</h4>
</div>
<div class="chestOpenerUncommon" id="div1" ondrop="drop(event)" ondragover="allowDropUncommon(event)">
<h4>Open your Uncommon chests here!</h4>
</div>
<div class="chestOpenerRare" id="div1" ondrop="drop(event)" ondragover="allowDropRare(event)">
<h4>Open your Rare chests here!</h4>
</div>
<div class="chestOpenerExotic" id="div1" ondrop="drop(event)" ondragover="allowDropExotic(event)">
<h4>Open your Exotic chests here!</h4>
</div>

JS:

function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function allowDropCommon(ev) {
event.preventDefault();
accept: '#normalChest';
};
function allowDropUncommon(ev) {
event.preventDefault();
accept: '#uncommonChest';
};
function allowDropRare(ev) {
event.preventDefault();
accept: '#rareChest';
};
function allowDropExotic(ev) {
event.preventDefault();
accept: '#exoticChest';
};
function drop(ev) {
ev.preventDefault();
var data =
ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
randomNormalItem = normal[Math.floor(Math.random()*normal.length)];
inventory.push(randomNormalItem);
alert(inventory);
}

最佳答案

您需要向 drop 函数添加一些逻辑,以检查您放下的图像是否对应于正确的胸部。我认为您不需要那些 allowDropXXX 函数。

我已经根据您的示例代码创建了一个 jsfiddle(用可爱的猫替换了箱子):https://jsfiddle.net/ruh910b6/2/

关于javascript - 尝试只允许 1 张图像放入 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36696164/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com