是否可以使用 Javascript 检测在文本区域中选择了哪些文本?我希望仅在用户选择文本时显示用户控件
我写了一个跨浏览器的函数,用于在文本区域或文本输入中选择文本,经过反复试验,我认为最终版本是我见过的最好的版本。我之前在 Stack Overflow 上发布过几次。这是一个示例:是否有 Internet Explorer 批准的 selectionStart 和 selectionEnd 替代品?
要检测用户何时在文本区域中进行选择,您可以使用
select
事件:
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);
};
是的,你可以。它会很简单:
const textarea = document.querySelector("textarea")
textarea.addEventListener("select", () => {
const selection = textarea.value.substring(
textarea.selectionStart,
textarea.selectionEnd
)
console.log('Your selection:', selection)
})
见MDN。