search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
全局 wheel 事件被无条件 preventDefault() 后,会彻底禁用页面的垂直滚动能力
仅在水平滚动有意义时拦截事件,其余情况放行,交还给浏览器处理原生垂直滚动
Home Web Front-end JS Tutorial A complete solution for retaining the ability to scroll vertically while scrolling horizontally

A complete solution for retaining the ability to scroll vertically while scrolling horizontally

Apr 05, 2026 am 08:31 AM

实现水平滚动时保留垂直滚动能力的完整解决方案

本文提供一个健壮的水平滚动 JavaScript 实现,通过智能判断滚动方向与边界状态,确保用户既能向右滑动浏览内容,也能向上滚动返回顶部初始区域。

在实现自定义水平滚动(如 .info 区域)时,一个常见却容易被忽视的问题是:全局 wheel 事件被无条件 preventDefault() 后,会彻底禁用页面的垂直滚动能力——导致用户无法再向上滚动回到顶部的 .container 区域。

根本原因在于原始代码中:

scrollContainer.addEventListener("wheel", (evt) => {
  evt.preventDefault(); // ❌ 无差别阻止所有滚轮事件
  scrollContainer.scrollLeft += evt.deltaY;
});

这会让浏览器认为“所有滚轮操作都已由 JS 处理”,从而放弃默认的文档级垂直滚动行为,即使用户正试图向上滚动(evt.deltaY < 0)且 .info 已位于最左端(scrollLeft === 0)。

✅ 正确做法是:仅在水平滚动有意义时拦截事件,其余情况放行,交还给浏览器处理原生垂直滚动

以下是优化后的核心逻辑:

const scrollContainer = document.querySelector(".info");

scrollContainer.addEventListener("wheel", (evt) =&gt; {
  // 判断滚动方向:向下滚动(+)→ 向右;向上滚动(−)→ 向左
  const scrollingDown = evt.deltaY &gt; 0;

  // 判断是否已达右边界(无法再向右滚动)
  const isAtEnd = scrollContainer.scrollWidth &lt;= scrollContainer.scrollLeft + scrollContainer.offsetWidth;

  // ✅ 仅当满足以下任一条件时才执行水平滚动并阻止默认行为:
  //   • 向下滚动 且 未到右边界 → 可向右滚动
  //   • 向上滚动 且 未到左边界(scrollLeft &gt; 0)→ 可向左滚动
  if ((scrollingDown &amp;&amp; !isAtEnd) || (!scrollingDown &amp;&amp; scrollContainer.scrollLeft &gt; 0)) {
    evt.preventDefault();
    scrollContainer.scrollLeft += evt.deltaY;
  }
  // ❌ 其他情况(如向上滚动但已到最左,或向下滚动但已到最右)不调用 preventDefault()
  // → 浏览器将自动触发页面垂直滚动,用户可顺利返回顶部
});</p>
<p>? <strong>关键要点说明</strong>:</p>
<ul>
<li>scrollContainer.scrollLeft &gt; 0 比 !== 0 更稳妥(避免浮点误差),精准表示“尚未归位到起点”;</li>
<li>边界检测使用 scrollWidth &lt;= scrollLeft + offsetWidth 是标准、可靠的右边界判定方式;</li>
<li>无需额外监听 scroll 或 resize 事件——该逻辑在每次 wheel 触发时动态计算,天然响应布局变化。</li>
</ul>
<p>? <strong>进阶建议(可选增强)</strong>:</p>
<ul>
<li>添加 passive: false 显式声明(尽管现代 Chrome 默认为 false),提升兼容性:<pre class="brush:php;toolbar:false">scrollContainer.addEventListener("wheel", handler, { passive: false });
  • 若需支持触控板惯性滚动,可结合 scroll-behavior: smooth 与 CSS scroll-snap-type 提升体验;
  • 对于键盘导航(如 ArrowLeft/ArrowRight),建议补充 keydown 监听以保持无障碍一致性。
  • 通过这一改进,.info 区域获得可控的水平浏览能力,同时完全不干扰页面整体的垂直滚动流——用户可自由上下穿梭于标题区与横向内容区之间,真正实现「水平滚动不锁死页面」的用户体验目标。

    The above is the detailed content of A complete solution for retaining the ability to scroll vertically while scrolling horizontally. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]

    Hot AI Tools

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    ArtGPT

    ArtGPT

    AI image generator for creative art from text prompts.

    Stock Market GPT

    Stock Market GPT

    AI powered investment research for smarter decisions

    Popular tool

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    useEffect in MERN stack React application implements instant update of user information after login useEffect in MERN stack React application implements instant update of user information after login Apr 04, 2026 am 06:57 AM

    This tutorial deeply explores the problem of useEffect hook in the MERN stack React application. After the user logs in, the user information cannot be updated immediately, and the page needs to be refreshed to display the latest data. The article analyzes in detail the correct use of the useEffect dependency array, points out common errors, and provides a dependency management solution based on user status changes to ensure that user information can be responded to and updated immediately after logging in, thereby improving the user experience.

    Dynamic data transfer and management within scripts in Node-RED UI templates Dynamic data transfer and management within scripts in Node-RED UI templates Apr 04, 2026 am 06:54 AM

    This article aims to solve the problem in Node-RED UI templates that cannot directly use Mustache syntax to dynamically inject JavaScript code within tags. We will explain the root cause and provide two safe and effective solutions: one is to directly access the passed data through $scope.msg, and the other is to render the data into JavaScript variables through Mustache combined with the | json filter. In addition, the article will also discuss the practice of encapsulating UI templates into subflows (Subflow) to achieve template reuse and centralized management.

    JavaScript form validation: use custom CSS classes for precise control JavaScript form validation: use custom CSS classes for precise control Apr 04, 2026 am 05:42 AM

    This tutorial dives into how to achieve precisely controlled form validation using pure JavaScript and custom CSS classes, rather than relying on browser default pseudo-classes. This article will analyze in detail the difference in verification timing between input and change events, and provide an optimization solution that effectively solves the problems of lagging verification status update and inaccurate class name assignment by combining the change event and the checkValidity() method, thereby achieving more flexible and user-friendly real-time form feedback.

    A complete solution for retaining the ability to scroll vertically while scrolling horizontally A complete solution for retaining the ability to scroll vertically while scrolling horizontally Apr 05, 2026 am 08:31 AM

    This article provides a robust horizontal scrolling JavaScript implementation that intelligently determines the scrolling direction and boundary status to ensure that users can not only slide to the right to browse the content, but also scroll up to return to the initial area at the top.

    A deep understanding of JavaScript array loops and their potential risks A deep understanding of JavaScript array loops and their potential risks Apr 04, 2026 am 06:42 AM

    This article aims to delve into the concept of looping arrays in JavaScript, its potential risks, and how to effectively avoid these problems. We'll clarify some common misunderstandings about looping arrays, show through code examples what situations can lead to infinite loops or stack overflows, and provide safe alternatives to help developers better understand and work with this type of data structure.

    A complete solution on how to implement product variations (such as sizes) and inventory limits in Stripe A complete solution on how to implement product variations (such as sizes) and inventory limits in Stripe Apr 05, 2026 am 08:36 AM

    Stripe's custom_fields are not suitable for product variant selection and inventory management; the correct approach is to create an independent Product/Price for each variant, and implement inventory verification, preemption and synchronization logic at the application layer.

    How to correctly understand and pass the parent node parameter to safely delete nodes in a binary search tree How to correctly understand and pass the parent node parameter to safely delete nodes in a binary search tree Apr 12, 2026 am 06:18 AM

    This article deeply analyzes the key role of the parentNode parameter in the BST node deletion operation, and explains why the current node must be explicitly passed in as the parent node when calling remove() recursively instead of using null - this is related to whether the minimum node in the subtree can be accurately located and the link can be safely broken.

    Storing Access Tokens in NextAuth Sessions: Security Considerations and Best Practices Storing Access Tokens in NextAuth Sessions: Security Considerations and Best Practices Apr 07, 2026 am 08:42 AM

    This article takes an in-depth look at the security and practices of storing access tokens in NextAuth sessions. By leveraging NextAuth's powerful JWT session strategy, access tokens are encrypted and securely managed. This article will provide detailed guidance on how to integrate custom authentication logic in NextAuth configuration, extend session data, and securely access these tokens on the client side. At the same time, key security best practices such as token rotation are emphasized to ensure the robustness and security of production-grade applications.

    Related articles