我想在JS中的拖放动作上创建一个精灵表动画。我试图通过将event.dataTransfer.setDragImage设置为以Sprite表作为背景(CSS)的div来实现。然后,我更改背景位置以使其具有动画效果。但是,当我开始拖动图像时,我只能看到第一个姿势。在开发工具中,我可以看到dom元素如何更新。为什么我的动画没有更新?我想念什么?
window.dragstart_handler = function (ev) {
ev.dataTransfer.setData("text/plain", ev.target.id);
let position = 0;
let interval = 500;
var elem = document.createElement("div");
elem.id = "dragContainer";
elem.textNode = "Dragging";
elem.style.position = "absolute";
document.body.appendChild(elem);
ev.dataTransfer.setDragImage(elem, 48, 48);
dragAnimationId = setInterval( () => {
document.getElementById("dragContainer").style.backgroundPosition = `-${position}px 0px`;
//we use the ES6 template literal to insert the variable "position"
if (position < 3552) {
position = position + 96;
} else {
position = 0;
}
}, interval );
}
window.dragend_handler = function (ev) {
console.log('dragend global');
nodeHitFn(ev);
}
// Let's remove the created ghost elem on dragend
document.addEventListener("dragend", function(e) {
var ghost = document.getElementById("dragContainer");
if (ghost.parentNode) {
ghost.parentNode.removeChild(ghost);
clearInterval(dragAnimationId);
}
}, false);