405

是否可以通过使用 jQuery 在网站的段落中获取突出显示的文本?

4

6 回答 6

555

获取用户选择的文本相对简单。使用 jQuery 并没有什么好处,因为您只需要windowanddocument对象。

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>

于 2011-03-21T14:57:23.347 回答
133

以这种方式获取突出显示的文本:

window.getSelection().toString()

当然还有一个特殊的处理,即:

document.selection.createRange().htmlText
于 2014-06-19T14:47:28.740 回答
13

如果您使用的是 chrome(无法验证其他浏览器)并且文本位于同一 DOM 元素中,则此解决方案有效:

window.getSelection().anchorNode.textContent.substring(
  window.getSelection().extentOffset, 
  window.getSelection().anchorOffset)
于 2012-03-20T20:02:13.930 回答
12

使用window.getSelection().toString().

您可以在developer.mozilla.org上阅读更多内容

于 2020-06-05T08:16:27.783 回答
8

是的,您可以使用简单的 JavaScript 片段来实现:

document.addEventListener('mouseup', event => {  
    if(window.getSelection().toString().length){
       let exactText = window.getSelection().toString();        
    }
}
于 2020-08-28T06:35:03.173 回答
1

如果需要,您可以使用事件

    document.addEventListener('selectionchange', (e)=>{
        console.log("Archor node - ",window.getSelection().anchorNode);
        console.log("Focus Node - ",window.getSelection().toString());
    });
于 2021-07-24T14:03:31.533 回答