HTML拖放API-

时间:2018-11-04 17:08:50

标签: javascript html api drag-and-drop

这是一个简单的数学游戏。

我的问题:我无法将图像拖到中间并将其拖到左侧。我在互联网上做了一些研究,但找不到任何结果。

HTML:

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="styleSheet.css" />
  <script src="myScript.js"></script>
</head>
<body>
  <!--İŞLEMLER-->
  <div id="islemler">
    <!--1.İŞLEM-->
    <div>
      <img src="images/question-mark.png" ondrop="dropHandler(event)" ondragover="dragoverHandler(event)">
      <img src="images/plus.png">
      <img src="images/question-mark.png" ondrop="dropHandler(event)" ondragover="dragoverHandler(event)">
      <img src="images/equal.png">
      <img src="images/eight.png">
    </div>


  </div>
  <!--TAŞINACAK RAKAMLAR-->
  <div id="tasinacakRakamlar">
    <img src="images/three.png" draggable="true" ondragstart="dragstartHandler(event)">
    <img src="images/five.png" draggable="true" ondragstart="dragstartHandler(event)">
  </div>
</body>
</html>

JS:

function dragstartHandler(e){
    e.dataTransfer.setData("text",e.target.id);
}

function dragoverHandler(e){
    e.preventDefault();
    //e.dataTransfer.dropEffect="copy";
}

function dropHandler(e){
    e.preventDefault();
    var myData = e.dataTransfer.getData("text");
    e.target.appendChild(document.getElementById(myData));
}

1 个答案:

答案 0 :(得分:0)

好吧,您尝试获取ElementByID,但是元素具有ID。 在您的元素上添加ID。

function dragstartHandler(e){
    e.dataTransfer.setData("text",e.target.id);
}

function dragoverHandler(e){
    e.preventDefault();
    //e.dataTransfer.dropEffect="copy";
}

function dropHandler(e){
    e.preventDefault();
    var myData = e.dataTransfer.getData("text");
    e.target.appendChild(document.getElementById(myData));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="styleSheet.css" />
  <script src="myScript.js"></script>
</head>
<body>
  <!--İŞLEMLER-->
  <div id="islemler">
    <!--1.İŞLEM-->
    <div>
      <img src="images/question-mark.png" ondrop="dropHandler(event)" ondragover="dragoverHandler(event)">
      <img src="images/plus.png">
      <img src="images/question-mark.png" ondrop="dropHandler(event)" ondragover="dragoverHandler(event)">
      <img src="images/equal.png">
      <img src="images/eight.png">
    </div>


  </div>
  <!--TAŞINACAK RAKAMLAR-->
  <div id="tasinacakRakamlar">
    <img src="images/three.png" draggable="true" id="ele1" ondragstart="dragstartHandler(event)">
    <img src="images/five.png" draggable="true" id="ele2" ondragstart="dragstartHandler(event)">
  </div>
</body>
</html>