如何使用jQuery选择文本 [英] How to select text with jQuery
本文介绍了如何使用jQuery选择文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何通过jQuery选择文本的一部分并进行处理?例如,我的文字为
How can I select a part of the text and process by jQuery? For example, I have a text as
<div id="test">This is an example text here</div>
我用鼠标选择了几个单词(不是整个div),并希望在其中显示这些单词(#test
的一部分)
I select few words (not the whole div) with mouse, and want to show these words (part of #test
) in
<div id="target"></div>
推荐答案
方法如下.以下内容适用于所有主流浏览器,包括IE 6.
Here's how. The following works in all major browsers, including IE 6.
function getSelectedText() {
var selectedText = "", sel;
if (window.getSelection) {
selectedText = "" + window.getSelection();
} else if ( (sel = document.selection) && sel.type == "Text") {
selectedText = sel.createRange().text;
}
return selectedText;
}
$('#target').text( getSelectedText() );
这篇关于如何使用jQuery选择文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文