為內容頁面添加鍵盤 ←/→ 鍵翻頁功能,提升用戶閱讀體驗。只需幾行代碼即可實現,兼容所有現代瀏覽器。
$(document).ready(function() {
// 獲取上一頁、下一頁鏈接的 href
var prevUrl = $('#prev').attr('href');
var nextUrl = $('#next').attr('href');
$(document).keydown(function(e) {
// 左鍵碼 37,右鍵碼 39
if (e.keyCode === 37 && prevUrl) {
window.location.href = prevUrl;
} else if (e.keyCode === 39 && nextUrl) {
window.location.href = nextUrl;
}
});
});
<!-- 頁面需包含 id 為 prev/next 的鏈接 -->
<p>上一篇:<a id="prev" href="/article/123">文章標題</a></p>
<p>下一篇:<a id="next" href="/article/125">文章標題</a></p>
e.which 兼容舊版 jQuery,現代建議 e.key === 'ArrowLeft'。if ($(e.target).is('input,textarea,select')) return;