gpt4 book ai didi

javascript - onDrop/onDragOver HTML5 更新 div

转载 作者:行者123 更新时间:2023-11-28 08:44:57 26 4
gpt4 key购买 nike

我使用 HTML5 onDrop 和 onDragOver 将图像从一个 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 在放置事件发生时显示/隐藏不同的 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>

最佳答案

我假设您尝试使用 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;
}

关于javascript - onDrop/onDragOver HTML5 更新 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19962508/

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