有時候我們需要把一段長文字自動切分到多個固定高度的區塊裡,模擬「分頁」的效果。做法並不複雜:先逐字塞入一個隱形的量測容器,觀察它的高度何時超出上限,超出的那一字就屬於下一頁。
*{margin:0;padding:0;}
body{line-height:24px;font-family:SimSun;font-size:12px;color:#000;}
#box1{height:96px;}
.box{width:200px;overflow:hidden;margin-top:10px;border:1px solid #000;}
.box 固定寬度並隱藏溢出,height 由 JS 動態指定;#box1 是首頁,其餘頁面會陸續被建立。
程式分成兩段。fnShowText 負責找出第一頁能容納到哪個字:建立一個臨時 div 放到 body 底下(可以同時參與排版取得真實高度),每次多塞一個字就量一次 offsetHeight,一旦超過 98px,就代表前一個字是切點。
var str = "這裡是一段話……(此處為測試用的長文字)";
var oBox1 = document.getElementById("box1");
function fnShowText() {
var newBox = document.createElement("div");
document.body.appendChild(newBox);
newBox.className = "box";
for (var i = 1; i <= str.length; i++) {
newBox.innerHTML = str.substring(0, i);
if (newBox.offsetHeight <= 98) {
oBox1.innerHTML = str.substring(0, i);
if (i == str.length) document.body.removeChild(newBox);
} else {
document.body.removeChild(newBox);
fnTextOver(i - 1); // 從上一個字開始處理後續頁面
break;
}
}
}
fnTextOver 則是同一套邏輯的延伸,只是起點由參數指定,並用 arguments.callee 遞迴呼叫自己,直到剩餘文字全部塞完為止:
function fnTextOver(n1) {
var newBox2 = document.createElement("div");
document.body.appendChild(newBox2);
newBox2.className = "box";
for (var i = n1; i <= str.length; i++) {
newBox2.innerHTML = str.substring(n1, i);
if (newBox2.offsetHeight <= 98) {
if (i == str.length) newBox2.style.height = "96px";
} else {
newBox2.innerHTML = str.substring(n1, i - 1);
newBox2.style.height = "96px";
arguments.callee(i - 1);
break;
}
}
}
fnShowText();
這種逐字量測的方式直觀,但每次都要觸發 reflow,文字量一大就會明顯變慢。另外 arguments.callee 在嚴格模式下已被禁用,建議改用具名函式遞迴。若只是要「溢出時顯示省略號」,直接用 CSS 的 text-overflow: ellipsis 會省下大量工本;若真的需要多欄分頁,現代做法會改用 Range API 或 CSS multi-column 來切割。