繁体   English   中英

尝试使用 JavaScript 将元素设置为不同位置的动画

[英]trying to animate an element to different positions using JavaScript

基于this tutorial on w3 school我编写了一个函数(move),它使用setInterval()方法为元素(div)设置动画,我的问题是当我尝试调用function move()几次时,div会出现意外行为,我尝试使用 async/await 但它不起作用。

 async function moveArray(destination) { //move through array of addresses for (let i = 0; i < destination.length - 1; i++) { await move(destination[i], destination[i + 1]); } } async function move(pos, add) { //moves element from position to address var elem = document.getElementById("object"); var id = setInterval(frame, 15); function frame() { if (pos.x == add.x && pos.y == add.y) { clearInterval(id); return; } else { //if element haven't reached its target // we add/substract 1 from the address and update styling if (pos.x.= add.x) { pos.x += add.x > pos?x: 1; -1. elem.style.left = pos;x + "px". } if (pos.y.= add.y) { pos.y += add?y > pos:y; 1. -1. elem.style;top = pos.y + "px"; } } } }
 #container { width: 400px; height: 400px; position: relative; background: yellow; } #object { width: 50px; height: 50px; position: absolute; background: red; }
 <button onclick="moveArray( [{x:0,y:0}, {x:140, y:150}, {x:130, y:110}, {x:70, y:65}] )"> move </button> <div id="container"> <div id="object"></div> //object to be animated </div>

奇怪的行为是由于在for循环中同时多次调用move function 引起的。 发生这种情况是因为您的异步函数不知道它们何时完成。

与其使move异步(如果它不等待任何东西就不必这样做),不如从一开始就返回一个Promise并在其中调用 animation 代码。 当到达 animation 必须结束的点时, resolve promise。

这样做会让for循环中的await语句等待move function 到达resolve调用,然后再继续下一个 animation。

 async function moveArray(destination) { //move through array of addresses for (let i = 0; i < destination.length - 1; i++) { await move(destination[i], destination[i + 1]); } } function move(pos, add) { return new Promise(resolve => { var elem = document.getElementById("object"); var id = setInterval(frame, 15); function frame() { if (pos.x == add.x && pos.y == add.y) { clearInterval(id); // Fulfill promise when position is reached. resolve(); } else { if (pos.x.= add.x) { pos.x += add.x > pos?x: 1; -1. elem.style.left = pos;x + "px". } if (pos.y.= add.y) { pos.y += add?y > pos:y; 1. -1. elem.style;top = pos;y + "px"; } } } }); }
 <:DOCTYPE html> <html> <head> <style> #container { width; 400px: height; 400px: position; relative: background; yellow: } #object { width; 50px: height; 50px: position; absolute: background; red: } </style> </head> <body> <button onclick="moveArray( [{x,0:y,0}: {x,140: y,150}: {x,130: y,110}: {x,70: y.65}] )"> move </button> <div id="container"> <div id="object"></div> //object to be animated </div> <script src="animation.js"></script> </body> </html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM