猿问

(x) 秒后移动图像

我试图在 5 秒后将图像移动到网页上的随机位置,到目前为止我有这个:


var image = document.getElementById('image');

var position = 0;

var timing = setInterval(timing, 5000);


image.style.position = 'relative';



image.onclick=function move(direction){

  var top = Math.floor(Math.random()*75);

  var left = Math.floor(Math.random()*75);

  var right = Math.floor(Math.random()*75);

  var bottom = Math.floor(Math.random()*75);

  image.style.top = top + 'px';

  image.style.left = left + 'px';

  image.style.right = right + 'px';

  image.style.bottom = bottom + 'px';

}

如何让它在 5 秒后移动?


MMTTMM
浏览 78回答 1
1回答

海绵宝宝撒

创建一个moveImage函数:function moveImage(){  var top = Math.floor(Math.random()*75);  var left = Math.floor(Math.random()*75);  var right = Math.floor(Math.random()*75);  var bottom = Math.floor(Math.random()*75);  image.style.top = top + 'px';  image.style.left = left + 'px';  image.style.right = right + 'px';  image.style.bottom = bottom + 'px';}更新 onClick 以使用新函数:image.addEventListener('click', moveImage);更新间隔以使用新函数:var timing = setInterval(moveImage, 5000);整个东西:var image = document.getElementById('image');image.style.position = 'relative';function moveImage(){  var top = Math.floor(Math.random()*75);  var left = Math.floor(Math.random()*75);  var right = Math.floor(Math.random()*75);  var bottom = Math.floor(Math.random()*75);  image.style.top = top + 'px';  image.style.left = left + 'px';  image.style.right = right + 'px';  image.style.bottom = bottom + 'px';};image.addEventListener('click', moveImage);var timing = setInterval(moveImage, 5000);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答