onDrop / onDragOver HTML5更新div

时间:2013-11-13 19:19:56

标签: javascript jquery html5

我正在使用HTML5 onDrop和onDragOver将图像从一个div标签移动到另一个div标签。

拖放脚本:

<script>
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));
}
</script>

这是div:

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
      <img src="ac.png" draggable="true" ondragstart="drag(event)" id="drag1" width="102" height="71"></div>
    <div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>

我还想使用这个jQuery在drop事件发生时显示/隐藏不同的div。我试图将.click更改为ondrop而没有运气。 我该怎么做?

<script>
// Wait for the document to load
$(document).ready(function() {
    // When one of our nav links is clicked on,
    $('#nav a').click(function(e) {
        div_to_activate = $(this).attr('href'); // Store its target
        $('.content:visible').hide(); // Hide any visible div with the class "content"
        $(div_to_activate).show(); // Show the target div
    });
});
</script>

1 个答案:

答案 0 :(得分:0)

我假设您尝试使用jQuery切换由drop事件触发的div的可见性:

DEMO

JS:

$(document).ready(function() {
  $('#div2').on("drop", function(e) {
    e.preventDefault();
    e.stopPropagation();
    if ($("#undropped:visible")) {
      $("#dropped").show();
      $("#undropped").hide();
    }
  });
});

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));
}

HTML:

<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>

<div id="undropped"><img src="https://placeholdit.imgix.net/~text?txtsize=13&txt=UNDROPPED&w=102&h=71"></div>

<div id="dropped"><img src="https://placeholdit.imgix.net/~text?txtsize=13&txt=DROPPED&w=102&h=71"></div>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
  <img src="https://placeholdit.imgix.net/~text?txtsize=33&txt=DRAG&w=102&h=71" draggable="true" ondragstart="drag(event)" id="drag1" width="102" height="71"></div>

CSS:

#div1 {
  clear: left;
}

#div2 {
  float: left;
  border: 1px solid #CCC;
  margin-bottom: 10px;
  height: 71px;
  width: 102px;
}

#undropped {
  margin-left: 10px;
  border: 1px solid #CCC;
  margin-bottom: 10px;
  height: 71px;
  width: 102px;
  float: left;
}

#dropped {
  margin-left: 10px;
  border: 1px solid #CCC;
  margin-bottom: 10px;
  height: 71px;
  width: 102px;
  float: left;
  display: none;
}