【问题标题】:How can I check to see if a div contains an image element in JavaScript? (Not like a background image, like the element contained)如何检查 div 是否包含 JavaScript 中的图像元素? (不像背景图片,像包含的元素)
【发布时间】:2018-11-25 23:35:10
【问题描述】:

我有一个相当简单的程序,可以在 6 个不同的瓷砖之间移动房子的图片。这里的目标如下:

  • 当我将房子拖到一个空的草地牢房时,我希望房子搬到那个牢房。 (这已经奏效了。)
  • 当我将房子拖到包含房子的单元格上时,我希望发生一些特别的事情。 (调用函数)

这是我的代码:

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

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

function yeet() {
  alert("ekfui");
}
.cell {
  border-radius: 10px;
  width: 100px;
  height: 100px;
  margin: 5px;
  padding: 5px;
  background-image: url("https://us.123rf.com/450wm/tuulijumala/tuulijumala1602/tuulijumala160200015/52473977-seamless-square-green-grass-texture-.jpg?ver=6");
}
<!--What you actually see-->
<div align="center">
  <table>
    <tr>
      <td>
        <div id="gh" class="cell" ondrop="drop(event)" ondragover="allowDrop(event)">
          <img src="http://worldartsme.com/images/free-house-clipart-1.jpg" draggable="true" ondragstart="drag(event)" id="drag1" width="100px" height="100px">
        </div>
      </td>

      <td>
        <div class="cell" ondrop="drop(event); yeet();" ondragover="allowDrop(event)"></div>
      </td>

      <td>
        <div class="cell" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
      </td>
    </tr>

    <tr>
      <td>
        <div class="cell" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
      </td>

      <td>
        <div class="cell" ondrop="drop(event)" ondragover="allowDrop(event)">
          <img src="http://worldartsme.com/images/free-house-clipart-1.jpg" draggable="true" ondragstart="drag(event)" id="drag2" width="100px" height="100px">
        </div>
      </td>

      <td>
        <div class="cell" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
      </td>
    </tr>

  </table>

</div>

请不要使用 jQuery 或库

【问题讨论】:

  • 检查 div 子级 .children 是否应该返回 div 拥有的所有子级的列表。

标签: javascript html draggable


【解决方案1】:

在你的 drop 函数中,检查事件 currentTarget 是否包含任何 img 标签:

if (ev.currentTarget.querySelectorAll('img').length > 0) {
  alert('There\'s already a house there.');
} else {
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}

https://jsfiddle.net/xmdkj0y4/

【讨论】:

    猜你喜欢
    • 2014-02-08
    • 2012-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    相关资源
    最近更新 更多