HowTo: CrossBrowser Cursor Position in Textareas

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- saved from url=(0045)http://www.dedestruct.com/cursorPosition.html -->
<HTML xmlns="http://www.w3.org/1999/xhtml"><HEAD>
<META content="text/html; charset=gb2312" http-equiv=Content-Type>
<SCRIPT language=JavaScript type=text/javascript>

function cursorPosition(){
    var textarea = document.getElementById("myTextArea");
    textarea.focus();
    // get selection in firefox, opera, ...

    if (typeof(textarea.selectionStart) == 'number')

    {    alert(textarea.selectionStart);
    }else if(document.selection){
        var selection_range = document.selection.createRange().duplicate();

        if (selection_range.parentElement() == textarea) {    // Check that the selection is actually in our textarea
        // Create three ranges, one containing all the text before the selection,
        // one containing all the text in the selection (this already exists), and one containing all
        // the text after the selection.
        var before_range = document.body.createTextRange();
        before_range.moveToElementText(textarea);                    // Selects all the text
        before_range.setEndPoint("EndToStart", selection_range);     // Moves the end where we need it

        var after_range = document.body.createTextRange();
        after_range.moveToElementText(textarea);                     // Selects all the text
        after_range.setEndPoint("StartToEnd", selection_range);      // Moves the start where we need it

        var before_finished = false, selection_finished = false, after_finished = false;
        var before_text, untrimmed_before_text, selection_text, untrimmed_selection_text, after_text, untrimmed_after_text;

        // Load the text values we need to compare
        before_text = untrimmed_before_text = before_range.text;
        selection_text = untrimmed_selection_text = selection_range.text;
        after_text = untrimmed_after_text = after_range.text;

        // Check each range for trimmed newlines by shrinking the range by 1 character and seeing
        // if the text property has changed.  If it has not changed then we know that IE has trimmed
        // a \r\n from the end.
        do {
          if (!before_finished) {
              if (before_range.compareEndPoints("StartToEnd", before_range) == 0) {
                  before_finished = true;
              } else {
                  before_range.moveEnd("character", -1)
                  if (before_range.text == before_text) {
                      untrimmed_before_text += "\r\n";
                  } else {
                      before_finished = true;
                  }
              }
          }
          if (!selection_finished) {
              if (selection_range.compareEndPoints("StartToEnd", selection_range) == 0) {
                  selection_finished = true;
              } else {
                  selection_range.moveEnd("character", -1)
                  if (selection_range.text == selection_text) {
                      untrimmed_selection_text += "\r\n";
                  } else {
                      selection_finished = true;
                  }
              }
          }
          if (!after_finished) {
              if (after_range.compareEndPoints("StartToEnd", after_range) == 0) {
                  after_finished = true;
              } else {
                  after_range.moveEnd("character", -1)
                  if (after_range.text == after_text) {
                      untrimmed_after_text += "\r\n";
                  } else {
                      after_finished = true;
                  }
              }
          }

        } while ((!before_finished || !selection_finished || !after_finished));

        // Untrimmed success test to make sure our results match what is actually in the textarea
        // This can be removed once you're confident it's working correctly
        var untrimmed_text = untrimmed_before_text + untrimmed_selection_text + untrimmed_after_text;
        var untrimmed_successful = false;
        if (textarea.value == untrimmed_text) {
          untrimmed_successful = true;
        }
        // ** END Untrimmed success test

        var startPoint = untrimmed_before_text.length;
        alert(startPoint);
        }
    }
}
    </SCRIPT>

<STYLE type=text/css>* {
    MARGIN: 20px
}
BODY {
    TEXT-ALIGN: center; MARGIN: 100px 0px; FONT-FAMILY: Verdana; FONT-SIZE: 10px
}
</STYLE>

<META name=GENERATOR content="MSHTML 8.00.6001.18702"></HEAD>
<BODY>
<H1>Cross-Browser Cursor Position in Textareas</H1>
<H3>This is a cross-browser script to get the location of the cursor within a
textarea</H3>
<FORM><TEXTAREA id=myTextArea rows=15 cols=75 name=myTextArea>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec ornare aliquam quam. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Pellentesque et quam in dui consequat tempor. Etiam lorem lectus, sollicitudin laoreet, tincidunt nec, pharetra in, magna. Mauris accumsan velit et augue. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</TEXTAREA>
</FORM><BUTTON onclick="cursorPosition();return false;" type=submit>Get the
cursor position</BUTTON>
<H4><A
href="http://www.dedestruct.com/2008/03/22/howto-cross-browser-cursor-position-in-textareas/">See
Original Blog Post &raquo;</A></H4></BODY></HTML>

http://www.dedestruct.com/cursorPosition.html

http://www.dedestruct.com/2008/03/22/howto-cross-browser-cursor-position-in-textareas/

http://parentnode.org/javascript/working-with-the-cursor-position/

http://alexking.org/blog/2003/06/02/inserting-at-the-cursor-using-javascript

Setting Cursor Position in a Textbox or TextArea with Javascript

http://blog.josh420.com/archives/2007/10/setting-cursor-position-in-a-textbox-or-textarea-with-javascript.aspx

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- saved from url=(0045)http://www.dedestruct.com/cursorPosition.html -->
<HTML xmlns="http://www.w3.org/1999/xhtml"><HEAD>
<META content="text/html; charset=gb2312" http-equiv=Content-Type>
<SCRIPT language=JavaScript type=text/javascript>

function cursorPosition(){
    var textarea = document.getElementById("myTextArea");
    textarea.focus();
    // get selection in firefox, opera, ...

    if (typeof(textarea.selectionStart) == 'number')

    {    //alert(textarea.selectionStart);
        textarea.value=textarea.value;
        setCaretPosition("myTextArea",textarea.selectionStart);
        return textarea.selectionStart;
    }else if(document.selection){
        var selection_range = document.selection.createRange().duplicate();

        if (selection_range.parentElement() == textarea) {    // Check that the selection is actually in our textarea
        // Create three ranges, one containing all the text before the selection,
        // one containing all the text in the selection (this already exists), and one containing all
        // the text after the selection.
        var before_range = document.body.createTextRange();
        before_range.moveToElementText(textarea);                    // Selects all the text
        before_range.setEndPoint("EndToStart", selection_range);     // Moves the end where we need it

        var after_range = document.body.createTextRange();
        after_range.moveToElementText(textarea);                     // Selects all the text
        after_range.setEndPoint("StartToEnd", selection_range);      // Moves the start where we need it

        var before_finished = false, selection_finished = false, after_finished = false;
        var before_text, untrimmed_before_text, selection_text, untrimmed_selection_text, after_text, untrimmed_after_text;

        // Load the text values we need to compare
        before_text = untrimmed_before_text = before_range.text;
        selection_text = untrimmed_selection_text = selection_range.text;
        after_text = untrimmed_after_text = after_range.text;

        // Check each range for trimmed newlines by shrinking the range by 1 character and seeing
        // if the text property has changed.  If it has not changed then we know that IE has trimmed
        // a \r\n from the end.
        do {
          if (!before_finished) {
              if (before_range.compareEndPoints("StartToEnd", before_range) == 0) {
                  before_finished = true;
              } else {
                  before_range.moveEnd("character", -1)
                  if (before_range.text == before_text) {
                      untrimmed_before_text += "\r\n";
                  } else {
                      before_finished = true;
                  }
              }
          }
          if (!selection_finished) {
              if (selection_range.compareEndPoints("StartToEnd", selection_range) == 0) {
                  selection_finished = true;
              } else {
                  selection_range.moveEnd("character", -1)
                  if (selection_range.text == selection_text) {
                      untrimmed_selection_text += "\r\n";
                  } else {
                      selection_finished = true;
                  }
              }
          }
          if (!after_finished) {
              if (after_range.compareEndPoints("StartToEnd", after_range) == 0) {
                  after_finished = true;
              } else {
                  after_range.moveEnd("character", -1)
                  if (after_range.text == after_text) {
                      untrimmed_after_text += "\r\n";
                  } else {
                      after_finished = true;
                  }
              }
          }

        } while ((!before_finished || !selection_finished || !after_finished));

        // Untrimmed success test to make sure our results match what is actually in the textarea
        // This can be removed once you're confident it's working correctly
        var untrimmed_text = untrimmed_before_text + untrimmed_selection_text + untrimmed_after_text;
        var untrimmed_successful = false;
        if (textarea.value == untrimmed_text) {
          untrimmed_successful = true;
        }
        // ** END Untrimmed success test

        var startPoint = untrimmed_before_text.length;
        //alert(startPoint);
        textarea.value=textarea.value;
        setCaretPosition("myTextArea",startPoint);
        return startPoint;
        }
    }
}

function setCaretPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}
    </SCRIPT>

<STYLE type=text/css>* {
    MARGIN: 20px
}
BODY {
    TEXT-ALIGN: center; MARGIN: 100px 0px; FONT-FAMILY: Verdana; FONT-SIZE: 10px
}
</STYLE>

<META name=GENERATOR content="MSHTML 8.00.6001.18702"></HEAD>
<BODY>
<H1>Cross-Browser Cursor Position in Textareas</H1>
<H3>This is a cross-browser script to get the location of the cursor within a
textarea</H3>
<FORM><TEXTAREA id=myTextArea rows=15 cols=75 name=myTextArea >Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec ornare aliquam quam. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Pellentesque et quam in dui consequat tempor. Etiam lorem lectus, sollicitudin laoreet, tincidunt nec, pharetra in, magna. Mauris accumsan velit et augue. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</TEXTAREA>
</FORM><BUTTON onclick="cursorPosition();return false;" type=submit>Get the
cursor position</BUTTON>
<H4><A
href="http://www.dedestruct.com/2008/03/22/howto-cross-browser-cursor-position-in-textareas/">See
Original Blog Post &raquo;</A></H4></BODY></HTML>

原文地址:https://www.cnblogs.com/emanlee/p/1689771.html