获取高亮显示/选中的文本

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

306230 次浏览

获取用户选择的文本相对简单。使用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>中的选择和文本<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>

这个解决方案工作,如果你使用chrome(不能验证其他浏览器),如果文本位于相同的DOM元素:

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

用这种方式高亮显示文本:

window.getSelection().toString()

当然,还有对ie的特殊处理:

document.selection.createRange().htmlText

使用window.getSelection().toString()

你可以在developer.mozilla.org上阅读更多

是的,你可以用简单的JavaScript代码片段:

document.addEventListener('mouseup', event => {
if(window.getSelection().toString().length){
let exactText = window.getSelection().toString();
}
}

如果需要,可以使用事件

    document.addEventListener('selectionchange', (e)=>{
console.log("Archor node - ",window.getSelection().anchorNode);
console.log("Focus Node - ",window.getSelection().toString());
});