scroll.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import { getOffset } from './offset';
  2. const locks = new Set();
  3. export function lockBodyScrolling(lockingEl) {
  4. locks.add(lockingEl);
  5. document.body.classList.add('sl-scroll-lock');
  6. }
  7. export function unlockBodyScrolling(lockingEl) {
  8. locks.delete(lockingEl);
  9. if (locks.size === 0) {
  10. document.body.classList.remove('sl-scroll-lock');
  11. }
  12. }
  13. export function scrollIntoView(element, container, direction = 'vertical', behavior = 'smooth') {
  14. const offset = getOffset(element, container);
  15. const offsetTop = offset.top + container.scrollTop;
  16. const offsetLeft = offset.left + container.scrollLeft;
  17. const minX = container.scrollLeft;
  18. const maxX = container.scrollLeft + container.offsetWidth;
  19. const minY = container.scrollTop;
  20. const maxY = container.scrollTop + container.offsetHeight;
  21. if (direction === 'horizontal' || direction === 'both') {
  22. if (offsetLeft < minX) {
  23. container.scrollTo({ left: offsetLeft, behavior });
  24. }
  25. else if (offsetLeft + element.clientWidth > maxX) {
  26. container.scrollTo({ left: offsetLeft - container.offsetWidth + element.clientWidth, behavior });
  27. }
  28. }
  29. if (direction === 'vertical' || direction === 'both') {
  30. if (offsetTop < minY) {
  31. container.scrollTo({ top: offsetTop, behavior });
  32. }
  33. else if (offsetTop + element.clientHeight > maxY) {
  34. container.scrollTo({ top: offsetTop - container.offsetHeight + element.clientHeight, behavior });
  35. }
  36. }
  37. }