手上拿到的是一份「乾淨」的 HTML——只有題目數據,沒有任何版型。目標是把它變成一份真正能用的線上試卷。
原始資料是一段結構化的 HTML,用 class 標示不同區塊:Desc 是說明、Problem 是題目、Choices 是選項。
<ol id="olThePaper"> <div class="Desc">選擇題:說明文字……</div> <div class="Problem" id="1"> <li>1. 你認為怎樣的老師是好老師?</li> <div class="Choices"> <label><input type="radio" name="prob1" value="A" />和學生平等相處……</label> <label><input type="radio" name="prob1" value="B" />所任教班成績優於平行班</label> </div> </div> <!-- 後續題目結構相同,id 2、3、4…… 亦可為 checkbox 多選或含 img 的圖片題 --> </ol>
核心用 JavaScript,實際上選擇了 jQuery 搭配 Aptana 作為 IDE,樣式則完全交給 CSS。頁面結構上,左頁 divLeft 與右頁 divRight 並排顯示,工具列負責翻頁與倒數。
/* YahooUI CSS Reset 這裡省略,重點是自建樣式 */
.Choices { line-height: 150%; margin: 5px 0; }
.Page { height: 500px; border: solid 1px gray; }
#olThePaper, .Display { padding: 0; width: 500px; }
/* .Display 與 #olThePaper 的寬度必須相同 */
.Display { float: left; }
#divToolbar { height: 35px; }
#divPrev, #divNext { float: left; width: 100px; height: 30px;
border: solid 1px green; background-color: #999999; }
#divPageInfo { float: left; width: 100px; height: 30px; }
#divTimer { float: left; width: 500px; height: 30px; }
整個排版邏輯封裝成一個建構函數,經紀工地接收試卷容器 id、題目 class、說明 class、選項 class,以及左右兩頁的 id。
function TTestPaperProcessor(PaperOlId, ProblemClass, DescClass, ChoicesClass, LeftPageId, RightPageId) {
this.FPaperOlId = PaperOlId;
this.FProblemClass = ProblemClass;
this.FDescClass = DescClass;
this.FChoicesClass = ChoicesClass;
this.FLeftPageId = LeftPageId;
this.FRightPageId = RightPageId;
$('#' + this.FLeftPageId).html('');
$('#' + this.FRightPageId).html('');
this._FormatProblemOptions();
this._DivideIntoPages();
this.setCurrPage(1);
}
關鍵想法是把選項區的寬度當成四個單位槽,依每個 label 的實際寬度判斷它該佔 1、2 還是 4 格,再塞進同一列。
_FormatProblemOptions: function() {
var mThis = this;
var mSelector = '.' + this.FProblemClass + ' .' + this.FChoicesClass;
$(mSelector).each(function() {
// 先依寬度由大到小排序,讓長選項優先佔位
var mLabels = jQuery.makeArray($('label', this));
mLabels.sort(function(First, Second) {
return $(Second).outerWidth(true) > $(First).outerWidth(true);
});
$(mLabels).appendTo(this);
var mSlots = -1; // 強制先建立一列
var mSlotWidth = $(mSelector).width() / 4.0;
var mCellSize = 0;
if (mThis._IsDisplayTableSupported()) {
while (mLabels.length > 0) {
if (mSlots <= 0) {
mCurrRow = $('<div class="___table" style="display: table;"></div>');
mCurrRow.appendTo(this);
mSlots = 4; mCellSize = 0;
var w = $(mLabels[0]).outerWidth(true);
if (w < mSlotWidth) mCellSize = 1;
if (w >= mSlotWidth && w < mSlotWidth * 2) mCellSize = 2;
if (w >= mSlotWidth * 2) mCellSize = 4;
}
mSlots -= mCellSize;
if (mSlots >= 0) {
mLabel = mLabels.shift();
$(mLabel).addClass('___cell');
$(mLabel).css('display', 'table-cell');
$(mLabel).appendTo(mCurrRow);
}
}
$('.___table').each(function() { // 平均分配寬度
$(this).css('width', '100%');
var mCellWidth = 100 / $('.___cell', this).length;
$('.___cell', this).css('width', mCellWidth + '%');
});
}
// IE6/7 不支援 display: table-cell,改走 table/tr/td 分支(邏輯相同,此處略)
});
}
為此還寫了個能力偵測,避免直接對舊版 IE 硬碰:
_IsDisplayTableSupported: function() {
if (this.FIsDisplayTableSupported != null) return this.FIsDisplayTableSupported;
this.FIsDisplayTableSupported = !(jQuery.browser.msie && jQuery.browser.version < 8.0);
return this.FIsDisplayTableSupported;
}
_CreateNewPage: function() {
++this.FPageCount;
mPage = $('<div class="' + this.CPageClass + '" id="___page_' + this.FPageCount + '"></div>');
mPage.appendTo($('#' + this.FPaperOlId));
return mPage;
},
_DivideIntoPages: function() {
var mProblems = $('.' + this.FProblemClass + ', .' + this.FDescClass);
var mCurrPage = this._CreateNewPage();
var mPageHeight = mCurrPage.outerHeight(true);
var mUsedPageHeight = 0;
for (var i = 0; i < mProblems.length; ++i) {
if (mUsedPageHeight + $(mProblems[i]).outerHeight(true) > mPageHeight) {
mCurrPage.hide();
mCurrPage = this._CreateNewPage();
mPageHeight = mCurrPage.outerHeight(true);
mUsedPageHeight = 0;
}
$(mProblems[i]).appendTo(mCurrPage);
mUsedPageHeight += $(mProblems[i]).outerHeight(true);
}
mCurrPage.hide();
}
這裡有個實作細節值得記下:高度必須用 outerHeight(true) 取得,而且初始化要放在 $(window).load() 而非 ready(),否則在 Chrome 與 Safari 上會拿到 0,導致分頁全盤錯亂。
setCurrPage: function(Value) {
this.FCurrPage = parseInt(Value / 2) * 2 + 1; // 轉成奇數頁碼
$('#' + this.FLeftPageId + ' .' + this.CPageClass).hide();
$('#' + this.FRightPageId + ' .' + this.CPageClass).hide();
$('#___page_' + this.FCurrPage).appendTo($('#' + this.FLeftPageId)).show('fast');
if (this.FCurrPage < this.FPageCount) {
++this.FCurrPage;
$('#___page_' + this.FCurrPage).appendTo($('#' + this.FRightPageId)).show('fast');
--this.FCurrPage;
}
},
Prev: function() { this.setCurrPage(this.FCurrPage - 2); },
Next: function() { this.setCurrPage(this.FCurrPage + 2); }
倒數計時直接借重 Keith Wood 的 countdown 插件,時間到就自動送出表單:
$(window).load(function() {
var obj = new TTestPaperProcessor('olThePaper', 'Problem', 'Desc', 'Choices', 'divLeft', 'divRight');
$('#divPrev').click(function() {
try { obj.Prev(); $('#divPageInfo').text(obj.getCurrPage() + ' of ' + obj.getPageCount()); }
catch (e) { alert('No such page!'); }
});
$('#divNext').click(function() {
try { obj.Next(); $('#divPageInfo').text(obj.getCurrPage() + ' of ' + obj.getPageCount()); }
catch (e) { alert('No such page!'); }
});
function TimeUp() { $('#formPaper').submit(); }
$('#divTimer').countdown({
until: '+90m', compact: true, format: 'HMS',
description: '', onExpiry: TimeUp
});
$('#divPageInfo').text(obj.getCurrPage() + ' of ' + obj.getPageCount());
});
整套機制的巧妙之處在於:它完全不碰題目內容,只依賴 class 約定與 DOM 尺寸計算。題幹裡塞圖片、表格、影片都不影響排版,因為分頁判斷的是渲染後的實際高度。跨瀏覽器的細節雖然瑣碎,但把差異收攏到能力偵測裡之後,主流程反而相當清爽。