萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 長文章自動分頁:依字元數切割與頁碼導覽

功能需求

  • 文章內容過長,需自動依指定字元數分頁。
  • 產生頁碼連結(1、2、3...),支援直接跳轉。
  • 保留 HTML 標籤完整性(避免標籤被切斷導致版面崩壞)。

核心函數:AutoPage

<%
Sub AutoPage()
  Dim MaxPageLen, page, content, PageNumber, ArticleID
  Dim contentLen, BeginPoint, EndPoint, i
  
  MaxPageLen = 1000 ' 每頁字元數
  content = UBBCode(rs("content")) ' 假設有 UBB 轉 HTML 函數
  ArticleID = rs("ArticleID")
  contentLen = Len(content)
  
  page = Request.QueryString("page")
  If page = "" Then page = 1 Else page = CInt(page)
  
  ' 計算總頁數
  PageNumber = Int(contentLen / MaxPageLen) + 1
  If contentLen Mod MaxPageLen = 0 And contentLen > 0 Then PageNumber = PageNumber - 1
  
  ' 邊界修正
  If page < 1 Then page = 1
  If page > PageNumber Then page = PageNumber
  
  ' 計算擷取範圍
  If page = 1 Then
    BeginPoint = 1
  Else
    BeginPoint = MaxPageLen * (page - 1) + 1
  End If
  
  If page = PageNumber Then
    EndPoint = contentLen
  Else
    EndPoint = MaxPageLen * page
    If EndPoint > contentLen Then EndPoint = contentLen
  End If
  
  ' 擷取並輸出當頁內容
  content = Mid(content, BeginPoint, EndPoint - BeginPoint + 1)
  Response.Write content & "


" ' 輸出頁碼導覽 For i = 1 To PageNumber Response.Write "" & i & " " Next End Sub %>

關鍵邏輯說明

變數說明
MaxPageLen每頁最大字元數,可依設計調整(如 2000、5000)。
BeginPoint/EndPoint使用 Mid 函數 1-based 索引擷取子字串。
PageNumber總頁數 = Int(總長度/每頁長度) + 1,修正整除情況。

⚠️ 重大缺陷:HTML 標籤被切斷

直接對 HTML 字串切割會導致標籤不完整(如 `

` 被切成 `

改進方案:HTML 感知分頁

方案 A:伺服器端使用 HTML 解析器(推薦)

  • 使用 MSHTML` (Microsoft HTML Object Library) 解析 DOM,遍歷節點累計文字長度,在安全邊界(文字節點、區塊元素結束)切分。
  • 或引入開源元件 HtmlAgilityPack(需 .NET 環境)。

方案 B:預先在內容插入分頁標記(手動/半自動)

編輯時在適當位置插入 ``,輸出時以此為界分頁(見下一篇文章)。

方案 C:前端 CSS 分頁(現代瀏覽器)

<style>
  .paged-content { column-width: 600px; column-gap: 2rem; }
  /* 或使用 CSS Paged Media 模組列印分頁 */
</style>

適合列印導向,不適合一般網頁閱讀。

進階:儲存分頁快取

將分頁後的 HTML 片段快存至資料表或檔案,避免每次請求重複切割運算。

ALTER TABLE Articles ADD PageCache TEXT; -- 儲存 JSON 陣列 ["page1html","page2html",...]
copyright © 萬盛學電腦網 all rights reserved