jQuery move Cursor Back “X” amount of Spaces

时光毁灭记忆、已成空白 提交于 2019-12-22 12:48:12

问题


I need it so that when a button is pressed, the cursor will:

1) Locate the end of the sentence 2) Move the cursor back from the end of the sentence "x" many spaces (x is a variable);

Here's a fiddle -----> 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
  });
});

回答1:


You'd do that like so :

$(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



来源:https://stackoverflow.com/questions/17636156/jquery-move-cursor-back-x-amount-of-spaces

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!