0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[js]スクロールをブロックしたい

Last updated at Posted at 2022-07-05

やりたいこと

ローディング表示中やアニメーション中にユーザーのスクロールをブロックしたい。

実装

bodyのoverflowをhiddenにすれば良いです!
reactではこんな感じで実装できた。

useEffect(() => {
  if (isScrollable) {
    document.body.style.overflow = "scroll";
  } else {
    document.body.style.overflow = "hidden";
  }
}, [isScrollable]);

うまくいかなかった例

スクロールのブロックはできるが、removeEventLisnerがなぜかうまくいかない。

useEffect(() => {
  const preventScroll = (e) => {
    e.preventDefault()
  }
  if (isScrollable) {
    document.removeEventListener('touchmove', preventScroll, { passive: false 
 });
    document.removeEventListener('wheel', preventScroll, { passive: false });
  } else {
    document.addEventListener('touchmove', preventScroll, { passive: false });
    document.addEventListener('wheel', preventScroll, { passive: false });
  }
}, [isScrollable])

* mousewheelは非推奨のためwheelを使っている
https://developer.mozilla.org/en-US/docs/Web/API/Element/mousewheel_event

* passiveはスクロールイベントを拾った時にユーザーのスクロールをブロックするかの指定。
https://blog.webico.work/passive-event-listeber01

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?