开发者

Problem with two JavaScript codes

开发者 https://www.devze.com 2023-01-06 02:28 出处:网络
I have these two codes - new function($) { $.fn.getCursorPosition = function() { var pos = 0; var el = $(this).get(0);

I have these two codes -

new function($) {
$.fn.getCursorPosition = function() {
var pos = 0;
var el = $(this).get(0);
// IE Support
if (document.selection) {
    el.focus();
    var Sel = document.selection.createRange();
    var SelLength = document.selection.createRange().text.length;
    Sel.moveStart('character', -el.value.length);
    pos = Sel.text.length - SelLength;
}
// Firefox support
else if (el.selectionStart || el.selectionStart == '0')
    pos = el.selectionStart;

return pos;
}
} (jQuery);

And

var element = document.getElementById('txtarr');
if( document.selection ){
      // The current selection
    var range = document.selection.createRange();
      // We'll use this as a 'dummy'
    var stored_range = range.duplicate();
      // Select all text
    stored_range.moveToElementText( element );
      // Now move 'dummy' end point to end point of original range
    stored_range.setEndPoint( 'EndToEnd', range );
      // Now we can calculate start and end points
    element.selectionStart = stored_range.text.length - range.text.length;
    element.selectionEnd = element.selectionStart + range.text.length;
}

The first one is for getting the cursor position in a textarea and the second one is for determining the end of a text开发者_JAVA技巧area ,but they give the same result? Where's the mistake?


I fix it.It's very simple :) . I just replace the second code(for determining the end of the textarea) with:$("#txtarr").val().length(jQuery).#txtarr is the id of mine textarea.


Both pieces of code are doing the same thing in slightly different ways. Each is attempting to get the position of the caret or selection in a textarea (or text input), although the first only gets the start position of the selection while the second gets both the start and end positions.

Both have flaky inferences: the first assumes a browser featuring document.selection will support TextRange, while the second makes the same inference plus another that assumes a browser without support for document.selection will have support for selectionStart and selectionEnd properties of textareas. Neither will correctly handle line breaks in IE. For code that does that, see my answer here: How to get the start and end points of selection in text area?

0

精彩评论

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