Lock or unlock your body scroll.
I have already try a lot of way to lock body scroll. Includes belows:
- Set document and body height 100%.
- Prevent scroll and touch event. ...
But none of these works for me.
Finally, I find a best way to achieve and I implement in this package.
If you want to know the detail, see below Theory section.
Use NPM or Yarn:
npm install lc-body-scroll-locker --save
yarn add lc-body-scroll-locker
Support TypeScript.
import bodyScrollLocker from 'lc-body-scroll-locker';
// lock body scroll
bodyScrollLocker.lock();
// unlock body scroll
bodyScrollLocker.unlock();
// see current lock status
console.log(bodyScrollLocker.isLocked);
IE9+
The theory in this package is quite simple.
Lock:
- Remember the scroll top position.
- Set body position fixed and transform: translate3d(0, -top.px, 0)).
Unlock:
- Clean body position and transform value.
- Set scroll top position.
- Document.body should not have margin. Use padding instead as possible.
- Run below command to start test server:
yarn serve
-
Manual test: Scroll page and click page will toggle lock status.
See console panel.
JamesYin, https://www.lazycoffee.com
MIT