---
title: "擴充 inobounce.js 套件，支援橫向滑動，處理 iOS 橡皮筋行為"
description: "說明如何擴充 iNoBounce.js 原始碼，在原有防止 iOS 橡皮筋回彈的基礎上，新增對橫向捲軸的支援，並修正 Chrome 桌面模擬模式的問題。"
canonical_url: "https://blog.markkulab.net/post/extnd-inobounce-js"
author: "Mark Ku"
author_url: "https://blog.markkulab.net/author/mark-ku"
site: "Mark Ku's Blog"
date_published: "2021-12-12T17:01:01.000Z"
date_modified: "2026-06-21T16:51:19.000Z"
category: "Frontend"
tags: ["inobounce", "ios", "bounce", "mobile web", "javascript", "scroll", "frontend", "webkit"]
language: "zh-TW"
license: "CC BY 4.0"
license_url: "https://creativecommons.org/licenses/by/4.0/"
attribution: "轉載或引用請註明作者並附上原文連結"
---

# 擴充 inobounce.js 套件，支援橫向滑動，處理 iOS 橡皮筋行為

> **TL;DR** — 擴充 inobounce.js 原始碼，新增橫向捲軸支援，並修正 Chrome 模擬器問題。此修改基於 inobounce.js 邏輯，解決了 iOS 橡皮筋效果在橫向捲動時的卡頓。

## 一、橡皮筋行為造成的問題
在開發 Mobile Web 時，經常碰到的 iOS 系統上的橡皮筋效果，這個效果搭配上拉刷新，下拉取得資料時，使用者體驗還是挺不錯的，但是實際上，每一個捲軸都擁有這效果，可能會額外造成滑動卡死及不流暢。  

* 捲軸捲最上方，會有彈簧的行為
![iOS 體育新聞應用程式介面，上方有橫向滑動分類選單](https://blog.markkulab.net/content/markku/posts/extnd-inobounce-js/images/bcjrxLU.png)
* 捲動到最下方，會有彈簧的行為
![iOS手機新聞應用程式介面顯示多則足球新聞](https://blog.markkulab.net/content/markku/posts/extnd-inobounce-js/images/6I9hQ8Y.png)
* 在多個侷部捲動，捲動溢出時會捲動不流暢，甚置造成捲動行為卡死。

## 二、常見的解決方案
對於 ios 原生來說只要一行程式碼，就能關閉彈簧行為，但對 web 來說，則是很麻煩的事。

### 解決方法 1.使用 css 的 fixed   
基於架構現有的手機版架構，所用到 px 都會被postcss工具轉換成 rem ，所以很難算到精準，所以不適合使用 fixed。
### 解決方法 2. 自己寫 js 控制  
全域阻止，還要一個個排外，太麻煩，改動的範圍太大了，且太花時間。
### 解決方法 3. 使用 inobounce js 套件
### 解決方法 4. 採用虛擬捲軸 (僅有特定情境能用)

## 參、inobounce js 的使用方式
### 步驟 1.針對 ios 裝置啟用 inobounce
```
if (this.isiOS) {
  inobounce.enable()
}
```

### 步驟 2. 針對捲動的容器下 css
1. overflow-x 或 overflow-y 值為 auto 或 scroll 
2. -webkit-overflow-scrolling 值為 touch

## 肆、採用 inobounce後，雖然解決了大部份的彈簧行為，但也衍伸了其他的問題，因此打算基於inobounce的邏輯，直接修改的原始碼。

### 問題 1. chrome 模擬 ios 時無法使用 touch ，調查了原始碼css 屬性在 chrome 中  -webkit-overflow-scrolling 沒有作用

```
var isDesktopDebugMode = window.navigator.vendor === 'Google Inc.'
      var scrolling = style.getPropertyValue('-webkit-overflow-scrolling') === 'touch' || isDesktopDebugMode
```
![開發者工具顯示 webkit-overflow-scrolling 屬性無效](https://blog.markkulab.net/content/markku/posts/extnd-inobounce-js/images/mRsCoi5.png)


### 問題 2. inobounce js 不支援橫向捲動，因此可以參考垂直捲軸的邏輯，來擴充橫向捲軸

### 伍、最後修改完的 inobounce js 如下

```
/*! iNoBounce - v0.2.1
 * https://github.com/lazd/iNoBounce/
 * Copyright (c) 2013 Larry Davis <lazdnet@gmail.com>; Licensed BSD */
(function(global) {
  // Stores the Y position where the touch started
  var startY = 0
  var startX = 0

  // Store enabled status
  var enabled = false

  var supportsPassiveOption = false
  try {
    var opts = Object.defineProperty({}, 'passive', {
      get: function() {
        supportsPassiveOption = true
      }
    })
    window.addEventListener('test', null, opts)
  } catch (e) {}

  var handleTouchmove = function(evt) {
    // Get the element that was scrolled upon
    var el = evt.target

    // Allow zooming
    var zoom = window.innerWidth / window.document.documentElement.clientWidth
    if (evt.touches.length > 1 || zoom !== 1) {
      return
    }

    // Check all parent elements for scrollability
    while (el !== document.body && el !== document) {
      // Get some style properties
      var style = window.getComputedStyle(el)

      if (!style) {
        // If we've encountered an element we can't compute the style for, get out
        break
      }

      // Ignore range input element
      if (el.nodeName === 'INPUT' && el.getAttribute('type') === 'range') {
        return
      }

      // chrome 在桌面版模擬 ios webkit-overflow-scrolling 屬性沒有作用
      var isDesktopDebugMode = window.navigator.vendor === 'Google Inc.'
      var scrolling = style.getPropertyValue('-webkit-overflow-scrolling') === 'touch' || isDesktopDebugMode

      var overflowY = style.getPropertyValue('overflow-y')
      var scrollableY = overflowY === 'auto' || overflowY === 'scroll'
      var height = parseInt(style.getPropertyValue('height'), 10)
      var width = parseInt(style.getPropertyValue('width'), 10)

      // Determine if the element should scroll

      var isScrollableY = scrolling && scrollableY

      var canScrollY = el.scrollHeight > el.offsetHeight // 能不能滑

      var curY = evt.touches ? evt.touches[0].screenY : evt.screenY

      if (isScrollableY && canScrollY) {
        // Get the current Y position of the touch

        // Determine if the user is trying to scroll past the top or bottom
        // In this case, the window will bounce, so we have to prevent scrolling completely
        var isAtTop = startY <= curY && el.scrollTop === 0
        var isAtBottom =
          startY >= curY && el.scrollHeight - el.scrollTop === height

        // Stop a bounce bug when at the bottom or top of the scrollable element
        if (isAtTop || isAtBottom) {
          console.log('prevent')
          evt.preventDefault()
        }

        // No need to continue up the DOM, we've done our job
        return
      }

      // 橫向捲動

      var overflowX = style.getPropertyValue('overflow-x')
      var scrollableX = overflowX === 'auto' || overflowX === 'scroll'
      var isScrollableX = scrolling && scrollableX
      var canScrollX = el.scrollWidth > el.offsetWidth

      if (isScrollableX && canScrollX) {
        // debugger
        // Get the current X position of the touch
        var curX = evt.touches ? evt.touches[0].screenX : evt.screenX

        // Determine if the user is trying to scroll past the top or bottom
        // In this case, the window will bounce, so we have to prevent scrolling completely
        var isAtLeft = startX <= curX && el.scrollLeft === 0
        var isAtRight =
          startX >= curX && el.scrollWidth - el.scrollLeft === width

        // Stop a bounce bug when at the bottom or top of the scrollable element
        if (isAtLeft || isAtRight) {
          evt.preventDefault()
        }

        // No need to continue up the DOM, we've done our job
        return
      }

      // Test the next parent
      el = el.parentNode
    }

    // Stop the bouncing -- no parents are scrollable
    evt.preventDefault()
  }

  var handleTouchstart = function(evt) {
    // Store the first Y position of the touch
    startY = evt.touches ? evt.touches[0].screenY : evt.screenY
    startX = evt.touches ? evt.touches[0].screenX : evt.screenX
  }

  var enable = function() {
    // Listen to a couple key touch events
    window.addEventListener(
      'touchstart',
      handleTouchstart,
      supportsPassiveOption ? { passive: false } : false
    )
    window.addEventListener(
      'touchmove',
      handleTouchmove,
      supportsPassiveOption ? { passive: false } : false
    )
    enabled = true
  }

  var disable = function() {
    // Stop listening
    window.removeEventListener('touchstart', handleTouchstart, false)
    window.removeEventListener('touchmove', handleTouchmove, false)
    enabled = false
  }

  var isEnabled = function() {
    return enabled
  }

  // Enable by default if the browser supports -webkit-overflow-scrolling
  // Test this by setting the property with JavaScript on an element that exists in the DOM
  // Then, see if the property is reflected in the computed style
  var testDiv = document.createElement('div')
  document.documentElement.appendChild(testDiv)
  testDiv.style.WebkitOverflowScrolling = 'touch'
  var scrollSupport =
    'getComputedStyle' in window &&
    window.getComputedStyle(testDiv)['-webkit-overflow-scrolling'] === 'touch'
  document.documentElement.removeChild(testDiv)

  if (scrollSupport) {
    enable()
  }

  // A module to support enabling/disabling iNoBounce
  var iNoBounce = {
    enable: enable,
    disable: disable,
    isEnabled: isEnabled
  }

  if (typeof module !== 'undefined' && module.exports) {
    // Node.js Support
    module.exports = iNoBounce
  }
  if (typeof global.define === 'function') {
    // AMD Support
    (function(define) {
      define('iNoBounce', [], function() {
        return iNoBounce
      })
    })(global.define)
  } else {
    // Browser support
    global.iNoBounce = iNoBounce
  }
})(this)
```

### 陸、結論
在 Web 看起來是無法完美避免橡皮筋行為，比較好的做法是改 Layout，捲到最上時用 CSS Fixed 住，回彈時，上面有東西擋住 滾動就沒這麼怪。

inobounce  js只能解決
* 第一次載入，上拉橡皮筋問題
* 多個侷部滑動時，捲動溢出卡死問題

暫時無法解決的問題  
* 當在滾動狀態時，滾動到最上方時或最下方，會出現一次橡皮筋行為，JS因為無法阻止滾動到負值，回彈後在 scrollTop 0 後，才會禁止橡皮筋行為。

---

## 關於本文與作者

本文出自 [Mark Ku's Blog](https://blog.markkulab.net/post/extnd-inobounce-js)

授權條款： [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) — 轉載或引用請註明作者並附上原文連結

### 關於作者

**[Mark Ku](https://blog.markkulab.net/author/mark-ku)** — 軟體工程師

- 10 年以上軟體工程師
- 做過北美電商與 AI SaaS 訂閱收費系統

### 作者開發的免費工具

以下工具皆可免費使用：

- [免費 PDF 簽名工具](https://blog.markkulab.net/tools/pdf-sign): 線上 PDF 簽名工具，瀏覽器內完成手繪、打字、上傳簽名，可拖曳放置、縮放、下載。所有處理都在你的裝置完成，檔案不會上傳。
- [VS Code Refactory](https://blog.markkulab.net/tools/refactory): Refactory 是一款 VS Code 重構擴充套件：34 個重構動作、37 條 code smell 檢查、Code Health 儀表板、18 種語言、534 支測試。懂你的專案慣例：介面放哪、DI 註冊寫在哪、'use client' 該不該加；還會用 git 修改頻率 × 複雜度排出「該先修哪個檔案」，並一鍵把壞味道交給你自己電腦上的 Claude Code 修。免費使用，原始碼不離開你的機器。
- [DB-Kit 資料庫管理工具](https://blog.markkulab.net/tools/db-kit): DB-Kit 是一個用 Tauri + Rust + React 打造的輕量跨平台資料庫管理工具，用單一一致的介面同時管理 MySQL、MariaDB、PostgreSQL、SQL Server、Oracle、SQLite、MongoDB、Redis、Kafka、Elasticsearch 與 RabbitMQ 十一種資料來源：連線密碼以 OS keychain 加密、SSH Tunnel、完整 CRUD、視覺化查詢建構器、多結果集同時顯示、跨連線資料傳輸、結構與資料比對（同步 SQL、結構快照）、Excel / CSV 匯入匯出、執行計畫視覺化、ER 圖、排程備份、SQL 壓力測試（p50～p99 延遲百分位）、15 條規則的 SQL 審查、執行前 AI 審查並逐句備份的「審查並執行」（自動產生回滾腳本）、Kafka 訊息瀏覽與監控告警、SSH 終端機與 SFTP / FTP、Docker / Kubernetes、遠端桌面（RDP / VNC / RustDesk）、檔案 / 資料夾比對、預存程序整合測試；六種介面語言，內建 AI 助手（本機 CLI 或 Anthropic / OpenAI 相容 API，自然語言生成 SQL、AI 審查與調校建議）與命令列工具 dbk。免費開源（MIT），提供 Windows / macOS / Linux 安裝檔。
- [VS Code Super Mermaid](https://blog.markkulab.net/tools/super-mermaid): Super Mermaid 是一款 VS Code 擴充套件：開箱即用的漂亮 Mermaid 圖表，自動上色、即時預覽、滑鼠平移縮放、PNG / SVG 高解析匯出，內建 21 種範本與多種主題。免費開源（MIT）。
- [React Super Mermaid](https://blog.markkulab.net/tools/react-super-mermaid): react-super-mermaid 是一個開源 React 元件庫：一行 <MermaidViewer> 即可渲染漂亮的 Mermaid 圖表，內建 colorful / sketch 主題、平移縮放、圖內搜尋、SVG / PNG 高解析匯出。輕量、SSR 安全、完整 TypeScript 型別。免費開源（MIT）。
- [Jira / Confluence Super Mermaid](https://blog.markkulab.net/tools/jira-super-mermaid): Atlassian Forge app：在 Jira issue 與 Confluence 內文直接寫 Mermaid 語法，畫流程圖、時序圖、狀態機與甘特圖。11 種圖表、SVG / PNG 匯出、明暗主題、完整中日韓文字支援。取得 Runs on Atlassian 資格：圖表存在你自己的站台，app 不呼叫任何第三方服務。免費，即將上架 Atlassian Marketplace。
- [Mermaid 線上預覽](https://blog.markkulab.net/tools/mermaid-preview): 在瀏覽器裡寫 Mermaid、即時看圖，整張圖表壓進網址就能分享。免註冊、不上傳伺服器，相容 mermaid.live 的分享連結。
- [React Intl Phone Number](https://blog.markkulab.net/tools/react-intl-phone-number): react-intl-phone-number 是一個開源 React 元件：framework-agnostic、不依賴 antd，提供 E.164 進出、可搜尋國旗 / 國碼下拉、可配置驗證等級（strict / mobile-strict / loose）、可主題化 CSS 與 i18n，電話邏輯由 google-libphonenumber 驅動。輕量、完整 TypeScript 型別。免費開源（MIT）。
- [Uptime Kuma Cluster](https://blog.markkulab.net/tools/uptime-kuma-cluster): 把單機版 Uptime Kuma 改造成高可用叢集：OpenResty + Lua 智慧負載平衡、MariaDB 共享狀態、健康檢查與自動 Failover，附監控與叢集管理 RESTful API，一行 Docker Compose 啟動。免費開源（MIT）。
- [AI Podcast Cut 音檔剪輯](https://blog.markkulab.net/tools/ai-podcast-cut): 丟進一段錄音，AI 幫你剪掉「嗯、呃、那個」與講到一半重講的片段，平衡逐段音量，並派第二個 agent 覆核每一刀。辨識與去人聲都在你自己的電腦上跑，不上傳、不需要金鑰。剪點會貼齊字邊界與零交越、每一刀都有漸弱漸強，句尾還留得住呼吸感。Windows / macOS / Linux 桌面應用，MIT 開源，Windows 安裝檔內建 ffmpeg。
- [AI Video Cut 影片剪輯](https://blog.markkulab.net/tools/ai-video-cut): 在影片裡選一個東西：打字（人臉、車牌、手機螢幕、logo）、手動點選或拖框，或交給 Claude Code / Codex 挑。AI Video Cut 會逐幀追蹤它，再幫你打馬賽克或模糊、調色、加跟著走的貼紙與文字、把螢幕或海報換成你的圖片或影片，甚至用其他幀拍到的背景把它移除。另有序列剪輯、本機字幕與 AI 助手。免費開源（MIT）的 Windows 桌面應用（macOS / Linux 實驗中），本機運行，影片不上傳。
- [open-pos 開源餐飲 POS](https://blog.markkulab.net/tools/open-pos): 一台電腦加一台出單機就能開店。資料存在自己的硬碟裡、沒有月租、沒有綁約，MIT 全開源。金額用整數元依營業稅法拆算稅額，銷售額加稅額恆等於總額；出單走網路型 ESC/POS（TCP 9100），不必裝廠商驅動。Tauri + Rust + SQLite 桌面應用，v1.0 開發中。
- [.NET 電商 API 架構範本](https://blog.markkulab.net/tools/dotnet-ecommerce-api): 以 .NET 10 打造的電商平台後端 API 架構範本：Controller → Service → Repository 分層、Autofac 依命名慣例自動註冊、SqlSugar 支援 MySQL / MariaDB 與 SQL Server、Redis 快取與訊息佇列、Hangfire 排程、JWT 認證，內建可擴充的金流 Provider 模組（綠界 ECPay、藍新 Newebpay）。Apache 2.0 開源。
- [Open Token Monitor 團隊 AI 用量監控](https://blog.markkulab.net/tools/open-token-monitor): 把每位員工電腦上 AI coding 工具的 token 用量與等值成本集中到公司自架的 hub：PostgreSQL、組織名單、依公司與部門比較的 dashboard、報表 API。員工端有 Electron 與 Rust/Tauri 兩種，每 30 分鐘自動上傳。MIT 開源，Docker 一行起。
- [AI 資安監控 ai-security-monitor](https://blog.markkulab.net/tools/ai-security-monitor): 網站上線了，漏洞、憑證與安全設定誰來檢查？ai-security-monitor 用自架 Security Hub 集中網站掃描與主機監控，合併重複發現、比對修補前後，讓你知道哪些問題還沒處理。

### 每日 Podcast

- [Mark's Tech Insights 每日 AI 新鮮事](https://blog.markkulab.net/category/tech-news): 每日精選 AI 與科技趨勢，透過語音摘要快速掌握最新技術動態，涵蓋 AI 應用、軟體架構、DevOps 與工程實戰。 — RSS: https://blog.markkulab.net/feed.xml
- [AI股市蝦聊](https://blog.markkulab.net/category/ai-stock-chat): 每個交易日用 AI 分析台股盤勢，以雙人對話聊當天的盤中觀察與隔日預測。 — RSS: https://blog.markkulab.net/ai-stock-chat/feed.xml
- [開源好物日報](https://blog.markkulab.net/category/open-source-weekly): 每天從 Hacker News、GitHub、Reddit 聲量雷達精選免費開源工具，以雙人對話聊解決什麼痛點與怎麼快速上手。 — RSS: https://blog.markkulab.net/open-source-weekly/feed.xml
- [AI 運動日報](https://blog.markkulab.net/category/sports-weekly): 每天以雙人對話聊 NBA、MLB 與國際體壇大事，台灣球迷視角，輕鬆有梗不酸人。 — RSS: https://blog.markkulab.net/sports-weekly/feed.xml
- [AI 國際新聞快報](https://blog.markkulab.net/category/world-news): 每天早上以雙人對話把過去一天的國際大事講白：政治外交、全球經濟、衝突與安全、災害與氣候，台灣視角、中立客觀、每則附出處。 — RSS: https://blog.markkulab.net/world-news/feed.xml
- [地端 AI 實驗室](https://blog.markkulab.net/category/local-ai-lab): 每天精選可以下載到自己機器上跑的開源模型與 LoRA，用雙人對話講清楚能用在哪些場景、你的顯卡跑不跑得動、跟同類差在哪，規格一律引述官方 model card。 — RSS: https://blog.markkulab.net/local-ai-lab/feed.xml
- [AI 行銷日報](https://blog.markkulab.net/category/ai-marketing): 每天以雙人對話整理最新 AI 在行銷、廣告、SEO／GEO 與內容行銷的大事，實戰視角、不業配、每則附出處。 — RSS: https://blog.markkulab.net/ai-marketing/feed.xml
- [AI 資安日報](https://blog.markkulab.net/category/ai-security): 每天以雙人對話整理最新 AI 與資安交會的大事：LLM 與 AI agent 漏洞、prompt injection、模型供應鏈、攻擊者怎麼用 AI，防禦視角、每則附出處。 — RSS: https://blog.markkulab.net/ai-security/feed.xml

### 電子報

[訂閱電子報](https://blog.markkulab.net/subscribe) — 第一時間收到新文章通知，無垃圾信、隨時可取消訂閱。
