HowTo: Cross-Browser 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>

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...