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

Dan*_*Dan 330 javascript jquery textselection

是否有可能在网站的段落中获取突出显示的文本,例如使用jQuery?

Tim*_*own 453

获取用户选择的文本相对简单.通过涉及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;
}
Run Code Online (Sandbox Code Playgroud)

如果您对同时处理选择<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();
};
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)

  • @Dan:对不起,我错过了这个问题(不要以为我提醒了我).第二个分支是IE <= 8(IE 9实现`window.getSelection()`).`document.selection.type`检查测试选择是文本选择而不是控件选择.在IE中,控件选择是包含一个或多个元素(例如图像和表单控件)的可编辑元素内的选择,其中包含轮廓和调整大小句柄.如果你在这样的选择上调用`.createRange()`,你得到一个`ControlRange`而不是`TextRange`,而`ControlRange`没有`text`属性. (28认同)
  • 如果{} -fork有用的话还有什么呢?什么是"控制"? (8认同)
  • @Auspex:我有点看到你的观点,但我不同意.jQuery插件是一个依赖于jQuery的库; 它本身不是jQuery.在选择处理的情况下,jQuery本身没有提供任何东西(这应该是因为选择处理不是jQuery的用途),所以任何使用jQuery的解决方案都是偶然使用它. (8认同)
  • @TimDown这是非常薄的冰,永远都说"jQuery没有X",因为当然,使用正确的插件,它可以做任何你可以在浏览器中用javascript做的事情.在这种情况下,我们有jquery.selection(http://madapaja.github.io/jquery.selection/).说"也不应该"也是错误的.我来到这里是因为我正在寻找这个.我有一个用例,jQuery是正确的解决方案. (2认同)
  • 我已经知道您知道以下内容,@TimDown,但应该注意的是,这不适用于 Firefox 中的“textarea”。这是一个[已知错误](https://bugzilla.mozilla.org/show_bug.cgi?id=85686)。 (2认同)

Par*_*Par 103

以这种方式获取高亮文本:

window.getSelection().toString()
Run Code Online (Sandbox Code Playgroud)

当然还有特殊待遇,即:

document.selection.createRange().htmlText
Run Code Online (Sandbox Code Playgroud)

  • 对于IE&gt; = 10,“`document.selection` _support已在IE10中删除,并替换为_” window.getSelection`”。来源:https://connect.microsoft.com/IE/feedback/details/795325/window-getselection-and-document-selection-legacy-support (2认同)
  • 这将在各种浏览器(例如 Firefox)的多种条件下失败。 (2认同)
  • [2020 年 8 月](https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection): _值得注意的是,目前 `getSelection()` 不适用于 ` Firefox、Edge(旧版)和 Internet Explorer 中的 &lt;textarea&gt;` 和 `&lt;input&gt;` 元素。可以使用“HTMLInputElement.setSelectionRange()”或selectionStart和selectionEnd属性来解决这个问题。_ (2认同)

Ebu*_*uka 11

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

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

  • 虽然确实如此,但这与旧答案有何不同?(对其他答案的评论并不总是有效,也适用于此处。) (4认同)

小智 10

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

window.getSelection().anchorNode.textContent.substring(
  window.getSelection().extentOffset, 
  window.getSelection().anchorOffset)
Run Code Online (Sandbox Code Playgroud)


MD *_*YON 10

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

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


小智 6

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

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