萬盛學電腦網

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

JavaScript 實現 @提及好友自動完成:光標定位、跨瀏覽器兼容與菜單交互完整方案

功能需求

  1. 輸入 @ 觸發好友搜索下拉菜單
  2. 光標進入已插入的 @好友 標籤時顯示菜單(支援再次編輯)
  3. Backspace 刪除時,若光標前為 @好友 標籤,顯示菜單允許修改
  4. 全瀏覽器兼容(IE6+、Firefox、Chrome、Safari)

核心難點與解法

難點解決方案
輸入框插入 HTML 標籤contenteditable div + document.execCommand('insertHTML') / IE range.pasteHTML
獲取光標前內容標準瀏覽器:Selection + Range;IE:document.selection.createRange()
菜單定位為每個 @標籤 生成唯一 ID,getBoundingClientRect() 獲取座標
跨瀏覽器事件對象統一 e = e || window.event,keyCode/which/charCode 兼容

關鍵代碼模塊

1. 獲取光標前內容(跨瀏覽器)

function getTextBeforeCursor(container) {
  var preceding = '', sel, range, precedingRange;
  if (window.getSelection) { // 標準
    sel = window.getSelection();
    if (sel.rangeCount > 0) {
      range = sel.getRangeAt(0).cloneRange();
      range.collapse(true);
      range.setStart(container, 0);
      preceding = range.cloneContents(); // DocumentFragment
    }
  } else if (document.selection) { // IE
    range = document.selection.createRange();
    precedingRange = range.duplicate();
    precedingRange.moveToElementText(container);
    precedingRange.setEndPoint('EndToStart', range);
    preceding = precedingRange.htmlText; // HTML 字符串
  }
  return preceding;
}

2. 插入 @標籤並顯示菜單

var atIndex = 0, curIndex = 0;

function insertAtTag() {
  var editor = document.getElementById('editor');
  var html = " @ ";
  
  if (document.selection && document.selection.createRange) { // IE
    var range = document.selection.createRange();
    range.pasteHTML(html);
  } else { // 標準
    document.execCommand('insertHTML', false, html);
  }
  
  showAtBox('at' + atIndex);
  curIndex = atIndex;
  atIndex++;
}

function showAtBox(spanId) {
  var span = document.getElementById(spanId);
  var pos = span.getBoundingClientRect();
  var editor = document.getElementById('editor');
  var editorPos = editor.getBoundingClientRect();
  
  var box = document.getElementById('at_box');
  box.style.left = (pos.left - editorPos.left) + 'px';
  box.style.top = (pos.bottom - editorPos.top) + 'px';
  box.style.display = 'block';
}

3. 鍵盤事件統一處理

document.getElementById('editor').addEventListener('keydown', function(e) {
  e = e || window.event;
  var key = e.keyCode || e.which || e.charCode;
  var isAt = (e.shiftKey && key === 50); // Shift+2 = @
  var isBackspace = (key === 8);
  var isEnter = (key === 13);
  var isArrowUp = (key === 38);
  var isArrowDown = (key === 40);
  
  if (isAt) {
    e.preventDefault(); // 阻止輸入 @ 字符
    insertAtTag();
    return;
  }
  
  if (isBackspace) {
    var before = getTextBeforeCursor(this);
    var lastNode = (before.nodeType === 11) // DocumentFragment
      ? before.lastChild 
      : (before.lastChild || null); // IE 返回字符串需轉換
    
    if (lastNode && lastNode.nodeType === 1 && lastNode.tagName === 'SPAN' 
        && lastNode.className === 'at_span') {
      e.preventDefault(); // 阻止默認刪除
      curIndex = parseInt(lastNode.id.slice(2));
      showAtBox(lastNode.id); // 顯示菜單允許修改
    } else {
      hideAtBox();
    }
    return;
  }
  
  // 方向鍵選擇菜單項
  if (isArrowUp || isArrowDown) {
    e.preventDefault();
    navigateAtBox(isArrowUp ? -1 : 1);
  }
  
  if (isEnter) {
    selectAtItem(); // 確認選擇
  }
});

4. 菜單導航與選擇

function navigateAtBox(step) {
  var items = document.querySelectorAll('.at_item');
  if (!items.length) return;
  
  var active = document.querySelector('.at_item.active');
  var idx = active ? Array.from(items).indexOf(active) : -1;
  idx = (idx + step + items.length) % items.length; // 循環
  
  if (active) active.classList.remove('active');
  items[idx].classList.add('active');
}

function selectAtItem() {
  var active = document.querySelector('.at_item.active');
  if (!active) return;
  
  var span = document.getElementById('at' + curIndex);
  span.textContent = '@' + active.textContent; // 替換 @ 為 @用戶名
  span.classList.add('at_mentioned'); // 標記已選
  hideAtBox();
}

function hideAtBox() {
  document.getElementById('at_box').style.display = 'none';
}

5. 滑鼠點擊標籤顯示菜單

document.getElementById('editor').addEventListener('click', function(e) {
  var target = e.target;
  if (target.classList.contains('at_span')) {
    curIndex = parseInt(target.id.slice(2));
    showAtBox(target.id);
  } else {
    hideAtBox();
  }
});

HTML 結構示例

<div id="editor" contenteditable="true" style="border:1px solid #ccc; min-height:100px; padding:10px;"></div>
<div id="at_box" class="at_dropdown" style="display:none; position:absolute; border:1px solid #ddd; background:#fff; z-index:999;">
  <div class="at_item" data-uid="1">張三</div>
  <div class="at_item" data-uid="2">李四</div>
  <div class="at_item" data-uid="3">王五</div>
</div>

<style>
.at_span { background:#eef; border-radius:3px; padding:0 2px; color:#36f; }
.at_mentioned { background:#dff; }
.at_item { padding:5px 10px; cursor:pointer; }
.at_item.active { background:#36f; color:#fff; }
</style>

現代框架對應實現提示

  • Vue/React:使用 contenteditable 封裝為受控組件,狀態管理用 prosemirror、slate 或 tiptap 等富文本框架,@提及作為 Node 類型內建支援。
  • 輕量級:@mention 文庫(如 tributejs、mention.js)基於 textarea + 絕對定位浮層,避開 contenteditable 坑點。

總結

原生 JS 實現 @提及的核心挑戰在於 contenteditable 的跨瀏覽器行為差異 與 光標/選區操作 API 的不統一。本文方案通過統一封裝 getTextBeforeCursor、insertHTML、定位邏輯,實現了 IE6+ 到現代瀏覽器的全兼容。生產環境強烈建議採用成熟富文本編輯器框架,避免重複造輪子並踩坑。

copyright © 萬盛學電腦網 all rights reserved