Detect selected text in a text area with javascript

若如初见. 提交于 2019-12-19 10:20:04

问题


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


回答1:


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?

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);
};


来源:https://stackoverflow.com/questions/5359451/detect-selected-text-in-a-text-area-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!