gpt4 book ai didi

javascript - 使用 Jquery 将信息附加到 `dataTransfer`

转载 作者:行者123 更新时间:2023-12-03 07:48:45 26 4
gpt4 key购买 nike

在拖拽开始时,我试图将文本附加到拖动的图像上。这样我就可以稍后在 drop 方法中识别它:

 var drag = function(event){
event.originalEvent.dataTransfer.setData('text', 'ww');

但不知何故,即使直接附加文本后,我也无法再访问它:它是未定义

 event.originalEvent.dataTransfer.getData('text')

如何将信息附加到 dataTransfer 对象并稍后在 drop 事件中访问它们? 谢谢

您可以尝试以下代码:

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

var drop = function(ev) {
var attached_text = ev.originalEvent.dataTransfer.getData("text");

//HERE I TRY TO GET THE ATTACHED TEXT
//ITS EMPTY
$('#attach_1').text(attached_text);
};


var drag = function(event){
event.originalEvent.dataTransfer.setData('text', 'ww');

var attached_text = (event.originalEvent.dataTransfer.getData('text'));

//RIGHT AFTER I ATTACHED THE TEXT ITS NOT ACCESIBLE
$('#attach_2').text(attached_text);
}


$('*[data-dragname="tree_icon_drag"]').on('drag', drag);

$('#drop').on('drop', drop);
$('#drop').on('dragover', allowDrop);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p id="attach_1"></p>
<p id="attach_2"></p>


<img src="http://agarwal.seas.upenn.edu/wp-content/uploads/2011/01/person_default_208x208-1.png" data-dragname="tree_icon_drag"/>


<div id="drop" style="background-color:red; width:300px; height:300px">

</div>

最佳答案

您在 dragstart 事件而不是 drag 事件中设置数据

var dragstart = function(event){
event.originalEvent.dataTransfer.setData('text', 'ww');
var attached_text = (event.originalEvent.dataTransfer.getData('text'));
$('#attach_2').text(attached_text);
};
$('*[data-dragname="tree_icon_drag"]').on('dragstart', dragstart);

演示

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

var drop = function(ev) {
var attached_text = ev.originalEvent.dataTransfer.getData("text");
$('#attach_1').text(attached_text);
};

var drag = function(event){};
var dragstart = function(event){
event.originalEvent.dataTransfer.setData('text', 'ww');
var attached_text = (event.originalEvent.dataTransfer.getData('text'));
$('#attach_2').text(attached_text);
};
$('*[data-dragname="tree_icon_drag"]')
.on('drag', drag)
.on('dragstart', dragstart);

$('#drop').on('drop', drop)
.on('dragover', allowDrop);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p id="attach_1"></p>
<p id="attach_2"></p>
<img src="http://agarwal.seas.upenn.edu/wp-content/uploads/2011/01/person_default_208x208-1.png" data-dragname="tree_icon_drag"/>
<div id="drop" style="background-color:red; width:300px; height:300px"></div>

关于javascript - 使用 Jquery 将信息附加到 `dataTransfer`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35093276/

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