您看到的问题是,img从未与left=100px
一起显示。在将更改绘制到DOM之前,其左样式立即设置为300px
。由于它从未出现在100px
,因此不需要过渡...在移动它之前,应至少在起始位置绘制一次。
[我正在写一个JS游戏,它通过设置IMG元素的x / y / width / height / opacity并允许CSS过渡逐渐将其移至目标并在事件到达时触发事件来移动IMG元素。这一切都很好。
我遇到麻烦的部分是创建新的IMG,并立即通过过渡将其移至目标。我已经尝试过,最好的办法是在目标位置已经创建图像,我怀疑是因为在将IMG添加到文档之前,目标样式已替换了源样式。
我如何创建具有以下内容的IMG:
我希望仅使用普通的JS,而不使用诸如JQuery之类的框架,因为这个游戏编写练习的目标是练习JS开发。
更新:根据要求,我的尝试失败之一。我尝试过以各种方式改组这些用逗号分隔的块,但是没有一个产生触发转换的预期结果。
function ThrowBall() { /* Create and configure an image. */ var img = document.createElement("img"); img.src = "https://www.thesunsetlounge.co.uk/Images/DiscoSpot.png" /* Set starting style. */ img.style.position = "fixed"; img.style.display = "block"; img.style.zIndex = "999"; img.style.top = "100px"; img.style.left = "100px"; /* Add to document. */ document.body.appendChild(img); /* Set transition. */ img.style.transition = "all 10s"; /* Move to target. */ img.style.left = "300px"; } /* Run. */ window.onload = ThrowBall;
更新#2:
感谢@Salketer的评论,我能够通过将将CSS和Transition-end事件设置为函数的代码并将该函数传递给
window.requestAnimationFrame
来解决我的问题。
[我正在写一个JS游戏,它通过设置IMG元素的x / y / width / height / opacity并允许CSS过渡逐渐将其移至目标并在事件到达时触发事件来移动IMG元素。 ...
您看到的问题是,img从未与left=100px
一起显示。在将更改绘制到DOM之前,其左样式立即设置为300px
。由于它从未出现在100px
,因此不需要过渡...在移动它之前,应至少在起始位置绘制一次。
function ThrowBall() { /* Create and configure an image. */ var img = document.createElement("img"); img.src = "https://www.thesunsetlounge.co.uk/Images/DiscoSpot.png" /* Set starting style. */ img.style.position = "fixed"; img.style.display = "block"; img.style.zIndex = "999"; img.style.top = "100px"; img.style.left = "100px"; /* Add to document. */ document.body.appendChild(img); /* Set transition. */ img.style.transition = "all 10s"; /* Move to target. */ window.requestAnimationFrame(()=>{img.style.left = "300px";}); } /* Run. */ window.onload = ThrowBall;
在两个样式定义之间添加延迟应该可以解决此问题。我使用了
requestAnimationFrame
,因为它是使用DOM的首选选择,但是在初始绘制图像后运行的任何东西都可以使用。像setTimeout(...,1000);
一样,但是您会看到图像静止一秒钟!
您看到的问题是,img从未与left=100px
一起显示。在将更改绘制到DOM之前,其左样式立即设置为300px
。由于它从未出现在100px
,因此不需要过渡...在移动它之前,应至少在起始位置绘制一次。