使用javascript检测文本区域中的选定文本 [英] Detect selected text in a text area with javascript
问题描述
是否可以使用Javascript检测在文本区域中选择了哪些文本?我希望仅在用户选择了文本时显示它们
Is it possible to detect what text has been selected in a text area using Javascript? I'm looking to show the user controls only when they have selected text
推荐答案
我已经编写了一个跨浏览器功能,用于获取文本区域或文本输入中选择的文本,经过一番反复研究后,我认为我见过的最好的一个.我已经几次将其发布在Stack Overflow上.这是一个示例:是否存在是Internet Explorer批准的selectionStart和selectionEnd的替代品?
I've written a cross-browser function for getting the text selected in a textarea or text input and after some toing and froing the final version is I think the best one I've seen. I've posted it on Stack Overflow a few times before. Here's one example: Is there an Internet Explorer approved substitute for selectionStart and selectionEnd?
要检测用户何时在文本区域中进行选择,可以使用 select
事件:
To detect when the user makes a selection in a textarea, you can use the select
event:
var textarea = document.getElementById("some_id");
textarea.onselect = function() {
var selection = getInputSelection(textarea);
var selectedText = textarea.value.slice(selection.start, selection.end);
console.log("Selected text: " + selectedText);
};
这篇关于使用javascript检测文本区域中的选定文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!