jsFiddle From the end, move th-6ren">
gpt4 book ai didi

javascript - jQuery 向后移动光标 "X"空格数量

转载 作者:行者123 更新时间:2023-11-29 19:51:30 26 4
gpt4 key购买 nike

我需要它,以便在按下按钮时,光标将:

1) 定位句末2)将光标从句尾“x”后移许多空格(x为变量);

这是一个 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
});
});

最佳答案

你会这样做:

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

关于javascript - jQuery 向后移动光标 "X"空格数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17636156/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com