Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
604 views
in Technique[技术] by (71.8m points)

how to modify the document selection in javascript?

I wanna modify the document selection (user currently selected by mouse or keyboard), how to do it in a cross browser way?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...