萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實現鍵盤左右鍵翻頁:提升閱讀體驗的輕量方案

應用場景

小說站、文章列表、圖片畫廊等分頁內容,支持鍵盤 ←/→ 快速翻頁,大幅提升用戶停留時長與 PV。

HTML 結構約定

<p>上一篇:<a id="pre" href="/article/123">文章標題</a></p>
<p>下一篇:<a id="next" href="/article/456">文章標題</a></p>

關鍵點:上一篇鏈接 id="pre",下一篇 id="next",無對應頁面時可省略或 href="#"。

核心 jQuery 代碼

$(function() {
  var $pre = $('#pre'), $next = $('#next');
  var prevHref = $pre.attr('href'), nextHref = $next.attr('href');

  $(document).on('keydown', function(e) {
    // 左鍵 37,右鍵 39
    if (e.keyCode === 37 && prevHref && prevHref !== '#') {
      location.href = prevHref;
    } else if (e.keyCode === 39 && nextHref && nextHref !== '#') {
      location.href = nextHref;
    }
  });
});

進階優化建議

  1. 防誤觸:輸入框焦點時禁用翻頁 if ($(e.target).is('input,textarea,select')) return;
  2. 視覺提示:頁面角落顯示「← 上一篇 / 下一篇 →」浮層,首次訪問自動消失。
  3. 預加載:滾動接近底部或鼠標懸停鏈接時預取下一頁 HTML。
  4. 無障礙:添加 aria-label、tabindex 支持屏幕閱讀器。

原生 JS 輕量版(無依賴)

document.addEventListener('keydown', function(e) {
  var target = e.target;
  if (target.tagName.match(/INPUT|TEXTAREA|SELECT/)) return;
  var prev = document.getElementById('pre');
  var next = document.getElementById('next');
  if (e.key === 'ArrowLeft' && prev?.href) location.href = prev.href;
  if (e.key === 'ArrowRight' && next?.href) location.href = next.href;
});

總結

鍵盤翻頁是「低成本、高收益」的體驗優化。核心邏輯不足 10 行,配合語義化 HTML 與防誤觸策略,即可為內容型網站帶來顯著的用戶體驗提升。

copyright © 萬盛學電腦網 all rights reserved