Skip to content

Commit cbb1ad5

Browse files
authored
fix: 2-ui/1.../09.../4.../ball-half/index.html
1 parent 7278a88 commit cbb1ad5

File tree

1 file changed

+15
-7
lines changed
  • 2-ui/1-document/09-size-and-scroll/4-put-ball-in-center/ball-half

1 file changed

+15
-7
lines changed

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

Lines changed: 15 additions & 7 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-
// ball.offsetWidth=0 before image loaded!
33-
// to fix: set width
34-
ball.style.left = Math.round(field.clientWidth / 2) + 'px'
35-
ball.style.top = Math.round(field.clientHeight / 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+
}
41+
};
42+
43+
updateBallPosition();
3644
</script>
3745

3846

0 commit comments

Comments
 (0)