You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在HTML中禁用用户滚动并保留程序控制的滚动?

Solution: Disable User Scrolling + Programmatic Scroll to Divs

Step 1: Disable All User-Initiated Scrolling

To lock out user-triggered scroll actions (mouse wheel, touch gestures, keyboard shortcuts), combine CSS and JavaScript for full coverage:

CSS Setup

Choose one of these based on your scrollbar preference:

  • Hide scrollbar entirely:
body {
  overflow: hidden;
  height: 100vh;
}
  • Keep scrollbar visible but non-interactive:
body {
  height: 100vh;
  overflow: auto;
  pointer-events: none; /* Blocks scrollbar interaction */
}
/* Re-enable interaction for clickable elements */
body button, body input, body a {
  pointer-events: auto;
}

JavaScript Event Blocking

Add this script to intercept and cancel user scroll triggers:

// Block mouse wheel
window.addEventListener('wheel', (e) => e.preventDefault(), { passive: false });

// Block keyboard scroll keys (arrows, space, page up/down, etc.)
window.addEventListener('keydown', (e) => {
  const scrollKeys = ['ArrowUp', 'ArrowDown', 'Space', 'PageUp', 'PageDown', 'Home', 'End'];
  if (scrollKeys.includes(e.key)) e.preventDefault();
});

// Block touch scroll gestures
window.addEventListener('touchmove', (e) => e.preventDefault(), { passive: false });

Step 2: Programmatic Scroll to Target Divs

Create a reusable function to scroll to any div by its ID:

Smooth Scroll Version

function scrollToSection(sectionId) {
  const target = document.getElementById(sectionId);
  if (target) {
    target.scrollIntoView({
      behavior: 'smooth',
      block: 'start' // Aligns element top with viewport top
    });
  }
}

Instant Scroll Version

function scrollToSection(sectionId) {
  const target = document.getElementById(sectionId);
  if (target) {
    window.scrollTo({
      top: target.offsetTop,
      behavior: 'auto' // Instant jump
    });
  }
}

Usage Example

Call the function when users make a story choice:

<button onclick="scrollToSection('chapter-forest')">Enter the forest</button>
<div id="chapter-forest">
  <!-- Forest chapter content here -->
</div>

Key Notes

  • Ensure all target divs have unique IDs.
  • The passive: false flag in event listeners is required to let preventDefault() work.
  • If using a custom scroll container (not window), apply CSS and event listeners to that container instead of body.

内容的提问来源于stack exchange,提问作者Shaken not Stirred

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 16:00:28