开发者

how to modify the document selection in javascript?

I wanna modify the document selection (user 开发者_如何学JAVAcurrently selected by mouse or keyboard), how to do it in a cross browser way?


I have not worked with text selection enough to provide real help, but what you are trying to do can be done. You will want to look into the following two functions:

  1. createRange() MSDN | MDC
  2. getRangeAt() MDC

I know it can be implemented cross browser. You can see some of it in action here:

http://fuelyourcoding.com/a-few-strategies-for-using-javascript/

By scrolling to the bottom and clicking the Elephant Icon, which uses the Evernote script. However, my script first selects the main content area (you will see it flash orange) and then it deselects once the capture is made.

Here is a mini jQuery plugin that does it. It was adapted by me from some site, and like the comments say, I feel horrible for not remembering. Its really important to note I adapted it to jQuery, but the code came from some site where they explained how to do it:

// Adapted this from somewhere. Feel horrible for not remembering.
$.fn.autoSelect = function(){
    var selectTarget = this[0]; // Select first element from jQuery collection
    if(selectTarget != null) {
         if(selectTarget.tagName == 'TEXTAREA' || (selectTarget.tagName == "INPUT" && selectTarget.type == "text")) {
             selectTarget.select();
         } else if(window.getSelection) { // FF, Safari, Opera
             var sel = window.getSelection();
             var range = document.createRange();
             range.selectNode(selectTarget);
             sel.removeAllRanges();
             sel.addRange(range);
         } else { // IE
             document.selection.empty();
             var range = document.body.createTextRange();
             range.moveToElementText(selectTarget);
             range.select();
         };
    };
    return this; // Don't break the chain
};

It seems this script is a few places online, but here is another variation on it


As an example, and the easiest one, let's say you want to move the user's selection to contain the contents of an element. The following will work in all major browsers:

function selectElementContents(el) {
    var body = document.body, range, sel;
    if (body.createTextRange) {
        range = body.createTextRange();
        range.moveToElementText(el);
        range.select();
    } else if (document.createRange && window.getSelection) {
        range = document.createRange();
        range.selectNodeContents(el);
        sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    }
}

selectElementContents( document.getElementById("someElement") );
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜