问题
Is it possible to get the selected text in an input box of a website, using either jQuery or vanilla JavaScript?
I have tried with var selectedText = window.getSelection().toString();
,
but this code only gets the text in a paragraph and not in an input box.
EDIT: Maybe I was unclear, I want to get the text from a website that I didn't create. I'm building a Chrome extension and I need to get the text from an input box of a website.
回答1:
Came with solution Find below
function disp() {
var text = document.getElementById("text");
var t = text.value.substr(text.selectionStart, text.selectionEnd - text.selectionStart);
alert(t);
}
<TEXTAREA id="text">Hello, How are You?</TEXTAREA><BR>
<INPUT type="button" onclick="disp()" value="show selected" />
回答2:
If you don't mind using jQuery plugins you can accomplish that by using this one http://madapaja.github.io/jquery.selection/
It's flexible (You can use it both for inputs and for paragraphs)
来源:https://stackoverflow.com/questions/32809168/get-selected-text-in-an-input-box