我试图使随机图像向上移动,然后回到它们原来的位置。
<script>
var looper = setInterval(animateAll, 2000, myArray);
function animateAll(myArray) {
// Gets a random image ID
var randomId = myArray[Math.floor(Math.random()*myArray.length)];
// Make that random icon bounce
bounce(randomId) ;
}
function bounce(randomId) {
var icon = document.getElementById(randomId)
var top = icon.offsetTop;
setTimeout ( icon.style.top = top-20 + "px", 500) ;
setTimeout ( icon.style.top = top + "px", 500) ;
}
</script> 这两条setTimeout行都可以正常工作。只有一行,好的图像将移动,而不返回到他们原来的位置。在这两行中,图像根本不会移动,可能是因为每一行之间都没有延迟。
谢谢你的帮助!
发布于 2016-05-09 21:14:39
问题是,您正在立即执行setTimeout调用中的代码。您实际上是在说“在500毫秒内执行设置icon.style.top = whatever的结果”.什么都不做。
试一试:
icon.style.top = top-20 + "px";
setTimeout ( function() { icon.style.top = top + "px"; }, 500) ;..。我在这事上浪费了15分钟,洛尔:
var steps = 7;
var increment = (Math.PI) / steps;
var bounceHeight = 20;
function doStep(icon, start, major, minor, height) {
if (minor == steps) {
major--;
height /= 2;
minor = 0;
icon.style.top = start;
}
if (major < 0) {
return;
}
if (minor < steps) {
pos = Math.sin((minor + 1) * increment);
icon.style.top = (start - height * pos) + "px";
setTimeout( function() { doStep(icon, start, major, minor + 1, height); }, 500/steps );
}
}
function bounce(randomId) {
var icon = document.getElementById(randomId)
var top = icon.offsetTop;
setTimeout ( function() { doStep(icon, top, 3, 0, bounceHeight); }, 500/steps ) ;
}https://stackoverflow.com/questions/37125419
复制相似问题