拖放:仅在正确匹配时才拖放
我进行了拖放操作,它运行得非常完美。但我有不同的物品只能放置在相应的放置区中。我怎样才能实现这个目标?
function ablegenErlauben(ev) {
ev.preventDefault();
}
function ablegen(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData('text');
var target = ev.target;
while (" "+target.className+" ".indexOf(" dropzone ") == -1) target = target.parentNode;
target.appendChild(document.getElementById(data));
}
window.addEventListener("load",function () {
var elms = document.querySelectorAll(".zielzone");
for (var i = 0; i < elms.length; i++) {
var zielzone = elms[i];
zielzone.addEventListener("drop",ablegen);
zielzone.addEventListener("dragover",ablegenErlauben);
};
elms = document.querySelectorAll("[draggable=true]")
for (var i = 0; i < elms.length; i++) {
var draggable = elms[i];
draggable.addEventListener("dragstart",ziehen);
};
});
I have this drag and drop and it runs perfect. But I have different items to drop only in their corresponding dropzones. How can I achieve this?
function ablegenErlauben(ev) {
ev.preventDefault();
}
function ablegen(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData('text');
var target = ev.target;
while (" "+target.className+" ".indexOf(" dropzone ") == -1) target = target.parentNode;
target.appendChild(document.getElementById(data));
}
window.addEventListener("load",function () {
var elms = document.querySelectorAll(".zielzone");
for (var i = 0; i < elms.length; i++) {
var zielzone = elms[i];
zielzone.addEventListener("drop",ablegen);
zielzone.addEventListener("dragover",ablegenErlauben);
};
elms = document.querySelectorAll("[draggable=true]")
for (var i = 0; i < elms.length; i++) {
var draggable = elms[i];
draggable.addEventListener("dragstart",ziehen);
};
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有几种方法可以处理这个问题,但总体来说还是要定义权限函数。在您的权限逻辑中,您可以将拖动的元素 id 与放置的元素 id 进行匹配,并执行逻辑。
在我的示例中,我创建了一个接受数组的第二个参数。在此数组中,如果容器位于拖动元素上,则可以定义容器 id;如果容器位于容器上,则可以定义拖动元素 id。然后在我的权限函数中,我将检查 array.includes(id),如果它返回 true 则允许删除它。小心拖放 API 的一些问题,例如放入 onDrop 的子元素中。
替代方案
为了补充我上面的答案,这里还有另一个可能实现您目标的替代方案,取自此 answer 它使用类来限制事件侦听器
There's a few ways to handle this, but overall will come down to defining the permission function. In your permission logic, you can match dragged element id with dropped element id, and execute the logic.
In my example I made a 2nd param which accept an array. In this array you can define the container id if it's on drag element, and drag element id if it's on container. Then in my permission function I'll just check with array.includes(id), if it's return true then it's allowed to be dropped. Careful with some gotchas of Drag and Drop API such dropping into child element of onDrop.
Alternative
To complement my answer above, here another alternative to probably achieve your goal, taken from this answer it uses class to limit event listener