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

发布于 2024-10-24 17:06:44 字数 39 浏览 4 评论 0原文

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

Is it possible to get the highlighted text in a paragraph of a website e.g. by using jQuery?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

水中月 2024-10-31 17:06:44

获取用户选择的文本相对简单。使用 jQuery 没有任何好处,因为除了 windowdocument 对象之外您不需要任何其他东西。

function getSelectionText() {
    let text = "";

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

    return text;
}

如果您对处理

function getSelectionText() {
    let text = "";
    const activeEl = document.activeElement;
    const 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>

Getting the text the user has selected is relatively simple. There's no benefit to be gained by involving jQuery since you need nothing other than the window and document objects.

function getSelectionText() {
    let text = "";

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

    return text;
}

If you're interested in an implementation that will also deal with selections in <textarea> and texty <input> elements, you could use the following. Since it's now 2016 I'm omitting the code required for IE <= 8 support but I've posted stuff for that in many places on SO.

function getSelectionText() {
    let text = "";
    const activeEl = document.activeElement;
    const 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>

风轻花落早 2024-10-31 17:06:44

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

window.getSelection().toString()

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

document.selection.createRange().htmlText

Get highlighted text this way:

window.getSelection().toString()

and of course a special treatment for ie:

document.selection.createRange().htmlText
酒儿 2024-10-31 17:06:44

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

您可以在 developer.mozilla.org 上了解更多信息

Use window.getSelection().toString().

You can read more on developer.mozilla.org

心奴独伤 2024-10-31 17:06:44

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

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

This solution works if you're using chrome (can't verify other browsers) and if the text is located in the same DOM Element:

window.getSelection().anchorNode.textContent.substring(
  window.getSelection().extentOffset, 
  window.getSelection().anchorOffset)
拥抱我好吗 2024-10-31 17:06:44

是的,您可以使用简单的 JavaScript 代码片段来做到这一点:

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

Yes you can do it with simple JavaScript snippet:

document.addEventListener('mouseup', event => {  
    if(window.getSelection().toString().length){
       let exactText = window.getSelection().toString();        
    }
}
白昼 2024-10-31 17:06:44

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

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

You can use an event if you want

    document.addEventListener('selectionchange', (e)=>{
        console.log("Archor node - ",window.getSelection().anchorNode);
        console.log("Focus Node - ",window.getSelection().toString());
    });
黯淡〆 2024-10-31 17:06:44

只要找到另一种方法就可以了。 window.getSelection() 的设计非常糟糕,令人沮丧。从第一天开始,它应该是一个基于文本的函数,而不是一个基于节点的函数。

让我们看一些非常基本的东西 - 您想要突出显示文本并使该部分变为粗体。太棒了,window.getSelection() 非常适合...一次。

然而,由于您还想让该文本的一部分变为斜体……好吧……现在您完蛋了。您想要突出显示的文本现在被划分在 2 个或可能更多的节点之间...当 window.getSelection() 给出的起点仅适用于指定的节点并且不考虑格式时,这是一个问题 - 的数量当文本被分成几个节点时,文本开头所在的节点右侧的字符......它变得一团糟。

您无法再完整地查找选定的短语,因为像 或
这样的标签将导致您找不到文本,或者,如果您在没有格式化的情况下查找,那么您现在需要循环遍历每个字符 - 甚至那么您可能有几段相同的文本,因此循环遍历节点不会帮助您到达应该对文本进行编辑的位置,因为您现在需要交叉引用格式化和未格式化的文本...

只是不要不要使用它,它是来自一个时代的垃圾,在这个时代,糟糕的程序员认为他们有责任规定你使用什么浏览器或如何突出显示文本 - 如果出现错误或错误,那是用户没有按照程序员的方式做事的错希望他们这样做。

从头开始自己编写更好的代码。

哎呀,即使是像将所有字母放入一个数组中,其中数组中的每个项目都是一个单独的字母,然后使用 onmousedown/onmouseup 决定起点和终点这样的事情也更简单更快,而不是如果您必须处理 window.onmousedown/onmouseup 。 getSelection() 完全是垃圾。

不幸的是,99% 的你想让它做的事情它都不适合。

如果使用 getSelected(text); 会好得多。返回第一个和最后一个字符以及所选文本的位置。或者将其分为 3 个独立的函数,以满足我的所有需求。

那会好一千倍。

Just find another way to do it. window.getSelection() is just frustratingly poorly designed. It should have been a text based function, not a node based function from day 1.

Let's take something really basic - you want to highlight a text an make that section bold. Great, window.getSelection() is fantastic for that...once.

However since you also want to make part of that text italic...well...now you're screwed. The text you want to highlight is now divided between 2 or potentially more nodes...which is an issue when the starting point given by window.getSelection() only applies to the specified node and does not take formating into account - the amount of characters to the right of the node that the beginging of the text is in when it's ivided up into several nodes...it just beecomes a fantastic mess.

You can no longer look up the selected phrase in it's entirety as tags like or
will result in you not finding the text, or, if you look up without formatting then you now need to loop through each and every character - and even then you may have several pieces of text that are the same, so looping through the nodes won't help you get where you should do your edits to the text anyways, since you now need to crossrefference formatted and unformatted text...

just don't use it, it's garbage from an era where bad programmers saw it as their duty to dictate what browser you use or how you should highlight text - and if something was buggy or wrong it's the users fault for not doing things the way the programmer wanted them to.

Code something better yourself from scratch instad.

Hell, even something like putting all the letters in an array where each item in the array is a seperate letter and then decide starting point and ending point with onmousedown/onmouseup is simpler an faster instead if you having to deal with window.getSelection() utter garbage is what it is.

It is woefully unfit for 99% of eeverything you want it to do.

It would have been so much better with `getSelected(text); returning the position of the first and last character as well as the selected text. Or divide it up in 3 seperate functions for all I care.

That woul have been a thousand times better.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文