2013-07-14 13 views
2

的量我需要它,以便当按钮被按下时,光标将:jQuery的移动光标返回“X”空间

1)找到句子 2)的端部移动光标背面从端句子“x”中有很多空格(x是变量);

这里有一个小提琴----->jsFiddle < ------

HTML

<span>From the end, move the cursor back this many spaces: </span> 
<input type='text' id='num' size='5'/> 
<button>Submit</button> 
<br/><br/> 
<textarea>The cursor will move in here</textarea> 

jQuery的

$(document).ready(function() { 
    $('button').click(function() { 
    var myval = parseInt($('#num').val()); //the number of spaces to move back 
    //code to move cursor back - starting from the END OF THE STATEMENT 
    }); 
}); 
+0

你见过这个:http://stackoverflow.com/questions/512528/set-cursor-position-in-html-textbox –

回答

2

你会做到这一点,像这样:

$(document).ready(function() { 
    $('button').click(function() { 
     var el  = $('textarea')[0], 
      myval = parseInt($('#num').val(), 10), 
      cur_pos = 0; 

     if (el.selectionStart) { 
      cur_pos = el.selectionStart; 
     } else if (document.selection) { 
      el.focus(); 

      var r = document.selection.createRange(); 
      if (r != null) { 
       var re = el.createTextRange(), 
        rc = re.duplicate(); 
       re.moveToBookmark(r.getBookmark()); 
       rc.setEndPoint('EndToStart', re); 

       cur_pos = rc.text.length; 
      } 
     } 

     if (el.setSelectionRange) { 
      el.focus(); 
      el.setSelectionRange(cur_pos-myval, cur_pos-myval); 
     } 
      else if (el.createTextRange) { 
      var range = el.createTextRange(); 
      range.collapse(true); 
      range.moveEnd('character', cur_pos-myval); 
      range.moveStart('character', cur_pos-myval); 
      range.select(); 
     } 
    }); 
}); 

FIDDLE