获取突出显示/选定的文本

是否有可能得到突出显示的文本在一个网站的段落,例如通过使用jQuery?

获取用户select的文本相对简单。 涉及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>元素中处理select的实现感兴趣,你可以使用下面的代码。 由于现在是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> 

以这种方式获得突出显示

 window.getSelection().toString() 

当然还有一个特殊的处理方法,

 document.selection.createRange().htmlText 

如果您使用chrome(无法validation其他浏览器)并且文本位于相同的DOM元素中,则此解决scheme可以工作:

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