为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

月关宝盒 2022-11-03 10:17:21
我正在制作一个基本游戏。单击此圆圈时,我需要在屏幕上移动另一个随机位置。剩下的游戏:https ://codepen.io/jtog95/pen/ExPbzvovar 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';}
查看完整描述

2 回答

?
浮云间

TA贡献1829条经验 获得超4个赞

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



查看完整回答
反对 回复 2022-11-03
?
慕田峪9158850

TA贡献1794条经验 获得超8个赞

带有 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() {

  spaceWidth = document.body.offsetHeight - parseInt(circle.style.height);

  spaceHeight = document.body.offsetWidth - parseInt(circle.style.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';

}


initCircle();

点击离开!:)


查看完整回答
反对 回复 2022-11-03
  • 2 回答
  • 0 关注
  • 117 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号