我找到了一个 jQuery 插件,它可以让我用完美的颜色突出显示我的文本。但现在我需要获取突出显示的文本选择并将其放在文本框中。
我发现这段代码正是我正在寻找的,尽管它没有选择我的颜色突出显示作为选择。
这是我找到并想要使用的代码,位于此链接http://www.codetoad.com/javascript_get_selected_text.asp#highlight2
我找到了一个 jQuery 插件,它可以让我用完美的颜色突出显示我的文本。但现在我需要获取突出显示的文本选择并将其放在文本框中。
我发现这段代码正是我正在寻找的,尽管它没有选择我的颜色突出显示作为选择。
这是我找到并想要使用的代码,位于此链接http://www.codetoad.com/javascript_get_selected_text.asp#highlight2
正如我所怀疑的,该插件“仅”将文本包装在一个跨度中。要访问该文本,您可以使用标准的 jQuery 选择器。基本上,它是这样工作的:
// the plugin generates new <span> elements with class="highlighted".
// You fetch all those with $('.highlighted.'). Then you get their text
// content by calling .text() [1]:
var text = $('.highlighted').text();
// Access your <textarea>, where you want to put the text into. Either
// use an ID element and use $('#id-of-textarea'), class or other means.
// to get the 1st one, use the ':eq(0)' jQuery selector (':eq(1)' for the
// second and so on) [2]. Then set the text with the jQuery .val() call [3]:
$('textarea:eq(0)'.val(text);
在您的问题中,您链接到getSelection()
方法及其亲属。如果您想通过鼠标访问用户选择的文本,这些都很好。
[1] http://api.jquery.com/text/