单击时如何随机化元素的位置

我正在制作一个基本游戏。单击此圆圈时,我需要在屏幕上移动另一个随机位置。


剩下的游戏:https ://codepen.io/jtog95/pen/ExPbzvo


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

var spaceWidth;

var spaceHeight;


initCircle();


function initCircle() {

  spaceWidth = screen.height - circle.height;

  spaceHeight = screen.width - circle.width;


  circle.addEventListener('click', moveCircle)

}


function moveCircle(){

  circle.style.top = Math.round(Math.random() * spaceWidth) + 'px';


  circle.style.left = Math.round(Math.random() * spaceHeight) + 'px';

}


月关宝盒
浏览 118回答 2
2回答

浮云间

我可以看到几个问题。首先是 circle.width 和 circle.height 未定义的事实。您可能应该改用 clientHeight 和 clientWidth 。我看到的第二个问题是在移动圈中。如果要使用顶部和左侧,则需要将位置设置为绝对或相对。完成这些更改后,您会注意到另一个问题,球可能会出界。这是因为您使用的是 screen.width 而不是 window.innerWidth (反之亦然)。

慕田峪9158850

带有 CSS 的 HTML(对于我的测试,使用你想要的,必须使用position):<div id="circle" style="position: absolute; height: 25px; width: 25px; border: 1px solid blue;"></div>javascript:var circle = document.getElementById('circle');var spaceWidth;var spaceHeight;function initCircle() {&nbsp; spaceWidth = document.body.offsetHeight - parseInt(circle.style.height);&nbsp; spaceHeight = document.body.offsetWidth - parseInt(circle.style.width);&nbsp; circle.addEventListener('click', moveCircle)}function moveCircle() {&nbsp; circle.style.top = Math.round(Math.random() * spaceWidth) + 'px';&nbsp; circle.style.left = Math.round(Math.random() * spaceHeight) + 'px';}initCircle();点击离开!:)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript