我正在编写一个带有反应的简单国际象棋游戏,并尝试使用拖放 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 usingdropBefore.replaceWith(yourNewChessPiece);
2
) are youMissing 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().... Ref和Node.replaceChild().
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);
关于javascript - JS拖拽: Dropping one element on top of another replaces dataTransfer data with first elements,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68105190/