@@ -41,39 +41,35 @@ export const addResizeObserver = (
4141) => {
4242 const { direction, timer } = options ;
4343 const [ debounceHandler , cleanTimer ] = debounce ( handler , timer ) ;
44- let h = debounceHandler ;
45- let lastWidth : number ;
46- let lastHeight : number ;
44+ let lastWidth : number = el . clientWidth ;
45+ let lastHeight : number = el . clientHeight ;
4746 if ( window . ResizeObserver ) {
48- if ( direction ) {
49- lastWidth = el . clientWidth ;
50- lastHeight = el . clientHeight ;
51- h = ( entry : { contentRect : { width : number ; height : number } } [ ] ) => {
52- if ( el ?. offsetParent === null ) {
53- options . lazy && el . setAttribute ( 'data-observer-hidden' , 'true' ) ;
54- return ;
55- }
47+ const h = ( entry : { contentRect : { width : number ; height : number } } [ ] ) => {
48+ const { width, height } = entry [ 0 ] . contentRect ;
49+ // 元素不可见(display:none)时跳过:offsetParent 为 null 且尺寸为 0
50+ if ( el ?. offsetParent === null && ! width && ! height ) {
51+ options . lazy && el . setAttribute ( 'data-observer-hidden' , 'true' ) ;
52+ return ;
53+ }
5654
57- if ( options . lazy && el . getAttribute ( 'data-observer-hidden' ) === 'true' ) {
58- el . removeAttribute ( 'data-observer-hidden' ) ;
59- return ;
55+ if ( options . lazy && el . getAttribute ( 'data-observer-hidden' ) === 'true' ) {
56+ el . removeAttribute ( 'data-observer-hidden' ) ;
57+ return ;
58+ }
59+ if ( width && direction === 'x' ) {
60+ if ( lastWidth !== width ) {
61+ debounceHandler ( entry ) ;
6062 }
61- const { width, height } = entry [ 0 ] . contentRect ;
62- if ( width && direction === 'x' ) {
63- if ( lastWidth !== width ) {
64- debounceHandler ( entry ) ;
65- }
66- } else if ( direction === 'y' ) {
67- if ( height && lastHeight !== height ) {
68- debounceHandler ( entry ) ;
69- }
70- } else if ( lastWidth !== width || lastHeight !== height ) {
71- debounceHandler ( entry , { x : lastWidth !== width , y : lastHeight !== height } ) ;
63+ } else if ( direction === 'y' ) {
64+ if ( height && lastHeight !== height ) {
65+ debounceHandler ( entry ) ;
7266 }
73- lastWidth = width ;
74- lastHeight = height ;
75- } ;
76- }
67+ } else if ( lastWidth !== width || lastHeight !== height ) {
68+ debounceHandler ( entry , { x : lastWidth !== width , y : lastHeight !== height } ) ;
69+ }
70+ lastWidth = width ;
71+ lastHeight = height ;
72+ } ;
7773 let observer : ResizeObserver | null = new ResizeObserver ( h as ResizeObserverCallback ) ;
7874 observer . observe ( el ) ;
7975 return ( ) => {
0 commit comments