簡體   English   中英

在Javascript中定位突出顯示的文本

[英]Targeting highlighted text in Javascript

尋找一種方法來定位所選文本並在Javascript中對其執行操作。 我應該使用什么樣的方法? 這是jQuery的工作嗎? 非常感謝!

編輯:早期的答案被視為針對CSS類。 我正在尋找點擊和突出顯示/選擇文本,然后在JS中采取行動。 謝謝!

編輯2:我被問到這個功能的一個例子。 這是一個,但代碼評論很差。 讓我知道你的想法。

嘗試window.getSelection ,你也應該閱讀SelectionRange

編寫跨瀏覽器,通用的“獲取選定文本”功能非常困難。 如果您可以限制您的要求僅說明在頁面中選擇的文本,那么生活就會更簡單。

但是如果你想從任何地方(內部表單控件,按鈕標簽,一般文本)中選擇文本,那么生活就很艱難。

這是我前段時間寫的一個函數,它適用於它所用的應用程序:

/* 
 *  This function returns the selected text in a document.
 *  If no text selected, returns an empty string.
 *
 *  Call on one of the following events: 
 *
 *     mouseup - most appropriate event
 *               for selection by mousedown, drag to select, mouseup
 *               may select only whitespace
 *
 *    dblclick - not as appropriate as mouseup
 *               for selection of word by double click
 *               may select only whitespace
 *
 *  Note that text can be selected in ways that do not dispatch
 *  an event, e.g. selecting all the text in the document using:
 *     ctrl + a
 *     context menu -> Select All
 *     edit menu -> Select All
 *     programmatically selecting text
 */
function checkForSelectedText(e) {
  var e = e || window.event;
  var el = e.target || e.srcElement;
  var tagName = el.tagName && el.tagName.toLowerCase();
  var t;
  var d = document;

  // Try DOM 2 Range - for most browsers, including IE 6+
  // However, doesn't get text selected inside form controls
  // that allow selection of text content (input type text, 
  // textarea)
  if (d && d.selection && d.selection.createRange) {
    t = d.selection.createRange().text;

  // Otherwise try HTML5 - note that getSelection returns
  // a string with extra properties. This may also get
  // text within input and textarea
  } else if (d.getSelection) {
    t = d.getSelection();
  }

  // If didn't get any text, see if event was inside
  // inupt@type=text or textarea and look for text
  if (t == '') {
    if (tagName == 'textarea' || 
       (tagName == 'input' && el.type == 'text')) {

     // Check selectionStart/End as otherwise if no text
     // selected, IE returns entire text of element
     if (typeof el.selectionStart == 'number' && 
         el.selectionStart != el.selectionEnd) {
        t = el.value.substring(el.selectionStart, el.selectionEnd)
     }
    }
  }
  return t;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM