jQuery move Cursor Back“X”空间量 [英] jQuery move Cursor Back "X" amount of Spaces
本文介绍了jQuery move Cursor Back“X”空间量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要它,以便当按下一个按钮时,光标将会:
I need it so that when a button is pressed, the cursor will:
1)找到句子的结尾
2)移动光标从句子x结束许多空格(x是一个变量);
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);
这里是一个小调-----> jsFiddle < ------
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
});
});
推荐答案
>
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();
}
});
});
这篇关于jQuery move Cursor Back“X”空间量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文