2011-03-21 121 views
257

是否可以在网站的某个段落中显示突出显示的文本,例如通过使用jQuery?获取突出显示/选定文本

+1

这里是一个有效的解决方案http://dipaksblogonline.blogspot.in/2014/11/javascript-text-selection-popover.html – Dipak 2014-11-28 18:30:15

+0

简单的JavaScript为我工作。 document.getSelection()。focusOffset-document.getSelection()。anchorOffset) – 2017-06-27 10:15:19

+0

@RohitVerma:这只是在简单的情况下工作包含在单个文本节点中的选择,这绝不是保证是这种情况。 – 2017-11-09 10:17:38

回答

358

获取用户选择的文本相对简单。涉及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>元素的实现,你可以使用以下。由于现在是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>

+7

如果{} -fork有什么好处呢?什么是“控制”? – Dan 2011-03-27 10:30:08

+25

@丹:对不起,我错过了这个问题(不要以为是让我知道)。第二个分支用于IE <= 8(IE 9实现'window.getSelection()')。 'document.selection.type'检查是测试选择是文本选择而不是控制选择。在IE中,控件选择是在包含一个或多个元素(如图像和表单控件)的可编辑元素中进行的选择,包含轮廓和调整大小手柄。如果你在这样的选择上调用'.createRange()',你会得到一个'ControlRange'而不是'TextRange',而'ControlRange's没有'text'属性。 – 2011-03-30 15:30:58

+0

任何事件发生后都可以调用此函数吗?它似乎并不适用于我在textarea – 2014-06-03 12:28:50

8

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

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

获取用这种方式突出显示的文字:

window.getSelection().toString() 

当然还有一个specia对于即l疗程:

document.selection.createRange().htmlText 
+0

对于IE> = 10“document.selection”_support已在IE10中删除,并替换为__“window.getSelection”。来源:https://connect.microsoft.com/IE/feedback/details/795325/window-getselection-and-document-selection-legacy-support – user2314737 2017-05-19 09:14:11

+0

这将在各种浏览器(例如Firefox)的多个条件下失败。 – Makyen 2017-08-12 07:33:01

相关问题