拖放替换图像

时间:2016-11-02 12:14:02

标签: javascript html html5 drag-and-drop draggable

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");
	if (ev.target.hasChildNodes()) {
		alert("This already contains a image");
	}
	else
	{
		ev.target.appendChild(document.getElementById(data));
	}
    
}
<!DOCTYPE html>
<html>

<head>
	<title>PUZZLE</title>
	<link rel="stylesheet" href="puzzletest.css">
	<script  type="text/javascript" src="puzzletest.js"></script>
</head>

<body>


	  <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
		<img id="drag2" src="puzzle12.jpeg" draggable="true" ondragstart="drag(event)" width="336" height="69">
	  </div>

		<img id="drag1" src="puzzle01.jpeg" draggable="true"ondragstart="drag(event)" width="336" height="69">

	 
</body>

</html>

当前HTML

  <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
    <img id="drag2" src="puzzle12.jpeg" draggable="true" ondragstart="drag(event)" width="336" height="69">
  </div>

    <img id="drag1" src="puzzle01.jpeg" draggable="true"ondragstart="drag(event)" width="336" height="69">

如何检查分区是否已包含图像,如果是,则应使用可拖动图像替换图像或打印警报?

正如你所看到的,如果我把一张图片放到另一张图片中,那就试试吧

1 个答案:

答案 0 :(得分:0)

问题在于ev.target.hasChildNodes() - target#drag2,但您需要div,因此请改用currentTarget

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");
  if (ev.currentTarget.hasChildNodes()) {
    alert("This already contains a image");
  }
  else
  {
    ev.target.appendChild(document.getElementById(data));
  }

}
<!DOCTYPE html>
<html>

  <head>
    <title>PUZZLE</title>
    <link rel="stylesheet" href="puzzletest.css">
    <script  type="text/javascript" src="puzzletest.js"></script>
  </head>

  <body>


    <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
      <img id="drag2" src="puzzle12.jpeg" draggable="true" ondragstart="drag(event)" width="336" height="69">
    </div>

    <img id="drag1" src="puzzle01.jpeg" draggable="true"ondragstart="drag(event)" width="336" height="69">


  </body>

</html>