JQuery.select() for <div>
http://api.jquery.com/select/ mentions that $().select()
"The select event is sent to an element when the user makes a text selection inside it. This event is limited to
<input type="text">
fields and&开发者_运维知识库lt;textarea>
boxes."
I am trying to detect text selection in <div>
.
What's the best way to provide the equilvalent $().select()?
Thanks in advance for your help.
A similar Q&A is posted here. You could use that function to get selected text in a div bound to the mouseup
javascript event.
E.g.
$('#div').mouseup(function() {
alert(getSelectedText());
});
// Get user selection text on page
function getSelectedText() {
if (window.getSelection) {
return window.getSelection();
}
else if (document.selection) {
return document.selection.createRange().text;
}
return '';
}
I use the following code in my pages:
if (document.selection)
{
text = document.selection.createRange().text;
}
else if (document.getSelection)
{
text = document.getSelection();
}
else if (window.getSelection)
{
text = window.getSelection();
}
else return;
It has some problems with newer versions of IE but other than that it's pretty good.
精彩评论