Skip to content

Commit fdefdd6

Browse files
authored
improve: fix ScrollLocker clac scroll bar size (#189)
* improve: fix ScrollLocker clac scroll bar size * improve judgement
1 parent c164995 commit fdefdd6

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

src/Dom/scrollLocker.ts

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,12 +71,16 @@ export default class ScrollLocker {
7171
}
7272

7373
let scrollBarSize = 0;
74+
const container = this.options?.container || document.body;
7475

75-
if (window.innerWidth - document.documentElement.clientWidth > 0) {
76+
if (
77+
(container === document.body &&
78+
window.innerWidth - document.documentElement.clientWidth > 0) ||
79+
container.scrollHeight > container.clientHeight
80+
) {
7681
scrollBarSize = getScrollBarSize();
7782
}
7883

79-
const container = this.options?.container || document.body;
8084
const containerClassName = container.className;
8185

8286
if (

tests/scrollLocker.test.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { spyElementPrototypes } from '../src/test/domHook';
12
import ScrollLocker from '../src/Dom/scrollLocker';
23

34
jest.mock('../src/getScrollBarSize', () =>
@@ -86,6 +87,15 @@ describe('ScrollLocker', () => {
8687
it('Lock multiple different target and container and unLock', () => {
8788
const testContainer = document.createElement('div');
8889

90+
const domSpy = spyElementPrototypes(HTMLDivElement, {
91+
scrollHeight: {
92+
get: () => 100,
93+
},
94+
clientWidth: {
95+
get: () => 90,
96+
},
97+
});
98+
8999
const locker1 = new ScrollLocker({
90100
container: testContainer,
91101
});
@@ -123,12 +133,23 @@ describe('ScrollLocker', () => {
123133
expect(document.body.getAttribute('style')).toBe(initialStyle);
124134
expect(testContainer.className).toBe('');
125135
expect(testContainer.getAttribute('style')).toBe(initialStyle);
136+
137+
domSpy.mockRestore();
126138
});
127139

128140
it('reLock', () => {
129141
scrollLocker.lock();
130142
const testContainer = document.createElement('div');
131143

144+
const domSpy = spyElementPrototypes(HTMLDivElement, {
145+
scrollHeight: {
146+
get: () => 100,
147+
},
148+
clientWidth: {
149+
get: () => 90,
150+
},
151+
});
152+
132153
expect(document.body.className).toBe(effectClassname);
133154
expect(document.body.getAttribute('style')).toBe(effectStyle);
134155

@@ -141,5 +162,7 @@ describe('ScrollLocker', () => {
141162

142163
expect(testContainer.className).toBe(effectClassname);
143164
expect(testContainer.getAttribute('style')).toBe(effectStyle);
165+
166+
domSpy.mockRestore();
144167
});
145168
});

0 commit comments

Comments
 (0)