如何在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: falseflag in event listeners is required to letpreventDefault()work. - If using a custom scroll container (not
window), apply CSS and event listeners to that container instead ofbody.
内容的提问来源于stack exchange,提问作者Shaken not Stirred
相关产品推荐
相关产品推荐

