开发者

jQuery retrieve the selected text

开发者 https://www.devze.com 2023-04-10 11:58 出处:网络
i apply this method to a开发者_开发问答 <textarea></textarea> element but i would like to return the html/text selected by the user.

i apply this method to a开发者_开发问答 <textarea></textarea> element but i would like to return the html/text selected by the user.

$('.wysiwyg textarea').live('select',function(text){
    console.log(text);
});

How can i do that using this method?


Found some useful code here:

http://mark.koli.ch/2009/09/use-javascript-and-jquery-to-get-user-selected-text.html

function getSelected(){
  var t = '';
  if(window.getSelection){
    t = window.getSelection();
  }else if(document.getSelection){
    t = document.getSelection();
  }else if(document.selection){
    t = document.selection.createRange().text;
  }
  return t.toString();
}

So you can do:

$('.wysiwyg textarea').live('select',function(){
    var text=getSelected();
    console.log(text);
});

As seen here:

http://jsfiddle.net/2SjRx/


You can use this :

    function SelectText(element) {
    var text = document.getElementById(element);
    if ($.browser.msie) {
        var range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if ($.browser.mozilla || $.browser.opera) {
        var selection = window.getSelection();
        var range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    } else if ($.browser.safari) {
        var selection = window.getSelection();
        selection.setBaseAndExtent(text, 0, text, 1);
    }
}

and finally bind the function accordingly

This should be enough to get you started http://jsfiddle.net/TXQmC/11/ its kinda late here so i only made the complete binding for firefox since is the one u using.


I didn't want to get the empty strings returned from some browsers, so I spent a few hours and updated the selection function. Tested to work with IE, Chrome, Firefox, Safari, Opera. Really wish jQuery had this built in so I wouldn't have to mess with it.

function getSelected() {
    var text = "";
    if (window.getSelection
    && window.getSelection().toString()
    && $(window.getSelection()).attr('type') != "Caret") {
        text = window.getSelection();
        return text;
    }
    else if (document.getSelection
    && document.getSelection().toString()
    && $(document.getSelection()).attr('type') != "Caret") {
        text = document.getSelection();
        return text;
    }
    else {
        var selection = document.selection && document.selection.createRange();

        if (!(typeof selection === "undefined")
        && selection.text
        && selection.text.toString()) {
            text = selection.text;
            return text;
        }
    }

    return false;
}
0

精彩评论

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

关注公众号