2 回答

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

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();
点击离开!:)
添加回答
举报