javascript - JS拖拽: Dropping one element on top of another replaces dataTransfer data with first elements

标签 javascript drag-and-drop data-transfer-objects

我正在编写一个带有反应的简单国际象棋游戏,并尝试使用拖放 API 来简化棋子的拖放。所有作品都按预期工作,除非一件作品捕捉到另一幅作品。例如,如果白车捕获黑兵,则白车移动到黑兵之前的位置,黑兵离开棋盘。但是下次我尝试移动白车时,它会移动被捕获的黑棋。
无论使用哪两个部分,此行为都是 100% 一致的。 Piece 1 捕获了piece 2,现在piece 1 的dataTransfer 数据就是piece2 的数据。
我已经缩小了范围,我认为问题在于 dataTransfer 对象。
棋子的dragStart代码

_onDragStart( e ){
    e.dataTransfer.items.clear();
    e.dataTransfer.clearData( "text/plain" );
    e.dataTransfer.effectAllowed = "move";
    e.dataTransfer.dropEffect = "move";
    e.dataTransfer.setData( "text/plain", JSON.stringify( this.metaData ) );
}
瓷砖放置处理程序的代码
_onDrop( e ){
    this.onDrop({
        index: this.state.index,
        piece: JSON.parse( e.dataTransfer.getData( "text/plain" ) )
    });
}

最佳答案

1) Try replace the old piece using dropBefore.replaceWith(yourNewChessPiece);

2) are you Missing the target element Id , not setting it, not sure if your metaData variable has it


一些 samples
// cache you element/variables to simplify the later
// I think you are missing this, I cant tell what your this.metaData holds
chessPieceToAddToTile = document.getElementById(data),
dropBefore = ev.target;

// using childNode.replaceWith() to insert the 
// so, *** REPLACE old piece with your new chessPieceToAddToTile Node
// dropBefore Node:
dropBefore.replaceWith(chessPieceToAddToTile);

childNode.replaceWith().... RefNode.replaceChild().
Drag Drop replace Node

Troubleshooting: Simplify it a bit so you can see what's happening, something like this in your drag handler, drop handlers

console.log("dragStart: dropEffect = " + ev.dataTransfer.dropEffect + " ; effectAllowed = " + ev.dataTransfer.effectAllowed ; chessPieceToAddToTile... blah blah);
DataTransfer

关于javascript - JS拖拽: Dropping one element on top of another replaces dataTransfer data with first elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68105190/

相关文章:

javascript - 更改全页 slider 库中的导航颜色

javascript - 每个循环中的字符串自动分割 - jquery

javascript - 通过http传输大量json

c# - 是否有任何框架或实用程序(在 .NET 空间中)用于从业务对象自动生成数据传输对象

design-patterns - 为什么应该将域实体与表示层隔离?

language-agnostic - 业务对象 - 容器还是功能?

javascript - .create 和 .save 之间的 Mongoose 区别

Android SDK : cannot add widgets to main. xml 通过拖放

iPhone:删除所需的缩略图以自定义完整的图像

javascript - HTML5 放置目标支持哪些剪贴板格式?