Skip to content

Commit 7278a88

Browse files
authored
fix: 2-ui/1-document/09.../4.../solution.view
1 parent 19769ac commit 7278a88

File tree

1 file changed

+14
-6
lines changed
  • 2-ui/1-document/09-size-and-scroll/4-put-ball-in-center/solution.view

1 file changed

+14
-6
lines changed

2-ui/1-document/09-size-and-scroll/4-put-ball-in-center/solution.view/index.html

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,21 @@
2626

2727

2828
<script>
29-
let ball = document.getElementById('ball')
30-
let field = document.getElementById('field')
31-
32-
window.onload = function() {
33-
ball.style.left = Math.round(field.clientWidth / 2 - ball.offsetWidth / 2) + 'px';
34-
ball.style.top = Math.round(field.clientHeight / 2 - ball.offsetHeight / 2) + 'px';
29+
const ball = document.getElementById('ball');
30+
const field = document.getElementById('field');
31+
32+
// 因为在图片加载完成前,ball.offsetWidth = 0,所以先判断获取到的 field 和 ball 宽度是否有值
33+
// 有值则进行计算,没值则在 100ms 后再次获取并判断,时间长短可自行设定
34+
const updateBallPosition = () => {
35+
if (field.clientWidth && ball.offsetWidth) {
36+
ball.style.left = Math.round(field.clientWidth / 2 - ball.offsetWidth / 2) + 'px';
37+
ball.style.top = Math.round(field.clientHeight / 2 - ball.offsetHeight / 2) + 'px';
38+
} else {
39+
setTimeout(updateBallPosition, 100);
40+
}
3541
};
42+
43+
updateBallPosition();
3644
</script>
3745

3846

0 commit comments

Comments
 (0)