相簿、小說、連載文章這類需要連續閱讀的頁面,很適合讓鍵盤接手翻頁:按左鍵回上一頁、右鍵去下一頁。原理不複雜,只要監聽按鍵事件,讀出 keyCode 後導向對應網址即可。
先在頁面上放好三個帶 id 的連結,再從 JS 讀取它們的 href:
<a id="last" href="<?=$lefturl?>">上一章</a>
<a id="booklist" href="<?=$booklisturl?>">返回目錄</a>
<a id="next" href="<?=$righturl?>">下一章</a>
<script language="javascript">
last = document.getElementById("last").href;
next = document.getElementById("next").href;
booklist = document.getElementById("booklist").href;
function keyUp(e) {
if (navigator.appName == "Microsoft Internet Explorer") {
var keycode = event.keyCode;
} else {
var keycode = e.which;
}
if (keycode == 39) window.location.href = next; // 右鍵 → 下一頁
if (keycode == 37) window.location.href = last; // 左鍵 → 上一頁
if (keycode == 13) window.location.href = booklist; // Enter → 目錄
}
document.onkeydown = keyUp;
</script>
如果不想手寫 id,可以用正則表達式從頁面 HTML 中擷取「上一頁」「下一頁」的連結位址:
var re = /<a href=["']?([-\w./?]+)["']?>[[(<]?上一頁[])>]?<\/a>/igm;
if (window.document.body.innerHTML.search(re) >= 0) {
var PREVIOUS_PAGE = RegExp.$1;
}
var re = /<a href=["']?([-\w./?]+)["']?>[[(<]?下一頁[])>]?<\/a>/igm;
if (window.document.body.innerHTML.search(re) >= 0) {
var NEXT_PAGE = RegExp.$1;
}
接著攔住輸入類元素,避免使用者打字時被誤觸翻頁:
if (typeof PREVIOUS_PAGE == "string" || typeof NEXT_PAGE == "string") {
document.onkeydown = function() {
switch (event.srcElement.tagName) {
case "INPUT":
case "TEXTAREA":
case "SELECT":
break;
default:
if (event.keyCode == 37 && typeof PREVIOUS_PAGE == "string") {
window.location.href = PREVIOUS_PAGE;
} else if (event.keyCode == 39 && typeof NEXT_PAGE == "string") {
window.location.href = NEXT_PAGE;
}
}
};
}
網路上大量 Code 只針對 IE 寫,其中常見的問題是對 a 標籤呼叫非標準的 .click():IE 會真的導向該連結的網址,Firefox 則不會(onclick() 雖可用,但那只是觸發 A 的 click 事件,不等於跳轉)。
解法是不要依賴 click(),直接把目標連結的 href 指派給 window.location.href:
var $ = function(id) { return document.getElementById(id); };
var hotKey = function(e) {
var e = e || event;
var k = e.keyCode || e.which || e.charCode; // 取得按鍵碼
if (k == 37) { // 左鍵
if ($("prevPage")) window.location.href = $("prevPage").href;
} else if (k == 39) { // 右鍵
if ($("nextPage")) window.location.href = $("nextPage").href;
} else if (k == 72) { // H 鍵回首頁
if ($("home")) window.location.href = $("home").href;
}
};
document.onkeydown = hotKey;
這個版本用 e || event 與 keyCode || which || charCode 同時兼容 IE 與非 IE 的事件模型,跨瀏覽器都能運作,也比正則擷取來得單純穩定。實作時記得同時在頁面上標示快捷鍵提示,並為螢幕閱讀器使用者保留可聚焦的連結,鍵盤操作才不會變成無障礙上的障礙。