Skip to content
This repository was archived by the owner on Nov 4, 2025. It is now read-only.

Commit 3f1af26

Browse files
authored
fix: Not align when element is invisible (#83)
* docs: Add test demo * fix invisible align * comment: add offsetParent reason
1 parent 14c5741 commit 3f1af26

File tree

2 files changed

+78
-1
lines changed

2 files changed

+78
-1
lines changed

examples/follow.js

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import React from 'react';
2+
import Align from '../src';
3+
4+
const Demo = () => {
5+
const [width, setWidth] = React.useState(100);
6+
const [height, setHeight] = React.useState(100);
7+
const [left, setLeft] = React.useState(100);
8+
const [top, setTop] = React.useState(100);
9+
const [visible, setVisible] = React.useState(true);
10+
11+
return (
12+
<div>
13+
<button
14+
type="button"
15+
onClick={() => {
16+
setLeft(`${Math.random() * 100}%`);
17+
setTop(`${Math.random() * 100}%`);
18+
setWidth(50 + Math.random() * 50);
19+
setHeight(50 + Math.random() * 50);
20+
}}
21+
>
22+
Random Size and Position
23+
</button>
24+
<button
25+
type="button"
26+
onClick={() => {
27+
setVisible(!visible);
28+
}}
29+
>
30+
Trigger Visible
31+
</button>
32+
33+
<div
34+
style={{
35+
border: '1px solid red',
36+
width: '90vw',
37+
height: '50vh',
38+
position: 'relative',
39+
}}
40+
>
41+
<div
42+
style={{
43+
width,
44+
height,
45+
border: '1px solid green',
46+
alignItems: 'center',
47+
justifyContent: 'center',
48+
position: 'absolute',
49+
left,
50+
top,
51+
display: visible ? 'flex' : 'none',
52+
}}
53+
id="content"
54+
>
55+
Content
56+
</div>
57+
58+
<Align
59+
target={() => document.getElementById('content')}
60+
align={{ points: ['tc', 'bc'] }}
61+
>
62+
<div
63+
style={{
64+
border: '1px solid blue',
65+
position: 'absolute',
66+
}}
67+
>
68+
Popup
69+
</div>
70+
</Align>
71+
</div>
72+
</div>
73+
);
74+
};
75+
76+
export default Demo;

src/Align.tsx

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,8 @@ const Align: React.RefForwardingComponent<RefAlign, AlignProps> = (
7878
// We should record activeElement and restore later
7979
const { activeElement } = document;
8080

81-
if (element) {
81+
// We only align when element is visible
82+
if (element && element.offsetParent) {
8283
result = alignElement(source, element, align);
8384
} else if (point) {
8485
result = alignPoint(source, point, align);

0 commit comments

Comments
 (0)