File tree Expand file tree Collapse file tree 1 file changed +15
-7
lines changed
2-ui/1-document/09-size-and-scroll/4-put-ball-in-center/ball-half Expand file tree Collapse file tree 1 file changed +15
-7
lines changed Original file line number Diff line number Diff line change 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
You can’t perform that action at this time.
0 commit comments