开发者

JQuery.select() for <div>

开发者 https://www.devze.com 2023-03-12 16:07 出处:网络
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\">

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消