2011-03-21 120 views
257

是否可以在網站的某個段落中顯示突出顯示的文本,例如通過使用jQuery?獲取突出顯示/選定文本

+1

這裏是一個有效的解決方案http://dipaksblogonline.blogspot.in/2014/11/javascript-text-selection-popover.html – Dipak 2014-11-28 18:30:15

+0

簡單的JavaScript爲我工作。 document.getSelection()。focusOffset-document.getSelection()。anchorOffset) – 2017-06-27 10:15:19

+0

@RohitVerma:這只是在簡單的情況下工作包含在單個文本節點中的選擇,這絕不是保證是這種情況。 – 2017-11-09 10:17:38

回答

358

獲取用戶選擇的文本相對簡單。涉及jQuery沒有任何好處,因爲除了windowdocument對象之外您什麼也不需要。

function getSelectionText() { 
    var text = ""; 
    if (window.getSelection) { 
     text = window.getSelection().toString(); 
    } else if (document.selection && document.selection.type != "Control") { 
     text = document.selection.createRange().text; 
    } 
    return text; 
} 

如果你有興趣,也將應對<textarea>選擇和textY處<input>元素的實現,你可以使用以下。由於現在是2016年,我省略了IE < = 8支持所需的代碼,但我已經在SO上的許多地方發佈了相關內容。

function getSelectionText() { 
 
    var text = ""; 
 
    var activeEl = document.activeElement; 
 
    var activeElTagName = activeEl ? activeEl.tagName.toLowerCase() : null; 
 
    if (
 
     (activeElTagName == "textarea") || (activeElTagName == "input" && 
 
     /^(?:text|search|password|tel|url)$/i.test(activeEl.type)) && 
 
     (typeof activeEl.selectionStart == "number") 
 
    ) { 
 
     text = activeEl.value.slice(activeEl.selectionStart, activeEl.selectionEnd); 
 
    } else if (window.getSelection) { 
 
     text = window.getSelection().toString(); 
 
    } 
 
    return text; 
 
} 
 

 
document.onmouseup = document.onkeyup = document.onselectionchange = function() { 
 
    document.getElementById("sel").value = getSelectionText(); 
 
};
Selection: 
 
<br> 
 
<textarea id="sel" rows="3" cols="50"></textarea> 
 
<p>Please select some text.</p> 
 
<input value="Some text in a text input"> 
 
<br> 
 
<input type="search" value="Some text in a search input"> 
 
<br> 
 
<input type="tel" value="4872349749823"> 
 
<br> 
 
<textarea>Some text in a textarea</textarea>

+7

如果{} -fork有什麼好處呢?什麼是「控制」? – Dan 2011-03-27 10:30:08

+25

@丹:對不起,我錯過了這個問題(不要以爲是讓我知道)。第二個分支用於IE <= 8(IE 9實現'window.getSelection()')。 'document.selection.type'檢查是測試選擇是文本選擇而不是控制選擇。在IE中,控件選擇是在包含一個或多個元素(如圖像和表單控件)的可編輯元素中進行的選擇,包含輪廓和調整大小手柄。如果你在這樣的選擇上調用'.createRange()',你會得到一個'ControlRange'而不是'TextRange',而'ControlRange's沒有'text'屬性。 – 2011-03-30 15:30:58

+0

任何事件發生後都可以調用此函數嗎?它似乎並不適用於我在textarea – 2014-06-03 12:28:50

8

此解決方案,如果您使用Chrome(無法驗證其他瀏覽器),如果文本位於同一DOM元素:

window.getSelection().anchorNode.textContent.substring(
    window.getSelection().extentOffset, 
    window.getSelection().anchorOffset) 
80

獲取用這種方式突出顯示的文字:

window.getSelection().toString() 

當然還有一個specia對於即l療程:

document.selection.createRange().htmlText 
+0

對於IE> = 10「document.selection」_support已在IE10中刪除,並替換爲__「window.getSelection」。來源:https://connect.microsoft.com/IE/feedback/details/795325/window-getselection-and-document-selection-legacy-support – user2314737 2017-05-19 09:14:11

+0

這將在各種瀏覽器(例如Firefox)的多個條件下失敗。 – Makyen 2017-08-12 07:33:01

相關問題