admin管理员组文章数量:1391934
I'm trying to implement a textarea which automatcally inserts close parens in React, but whenever I modify the textarea's value property, the cursor jumps to the end of the text being edited.
Here's my onChange function:
//on change
function(event) {
var newText = event.target.value
var cursorPosition = getCursorPosition(event.target)
if(lastCharacterWasParen(newText, cursorPosition)){
newText = newText.slice(0, cursorPosition) + ')' + newText.slice(cursorPosition)
}
this.setProps({text: newText}})
}
This successfully inserts the paren, but how do I preserve the cursor position?
I'm trying to implement a textarea which automatcally inserts close parens in React, but whenever I modify the textarea's value property, the cursor jumps to the end of the text being edited.
Here's my onChange function:
//on change
function(event) {
var newText = event.target.value
var cursorPosition = getCursorPosition(event.target)
if(lastCharacterWasParen(newText, cursorPosition)){
newText = newText.slice(0, cursorPosition) + ')' + newText.slice(cursorPosition)
}
this.setProps({text: newText}})
}
This successfully inserts the paren, but how do I preserve the cursor position?
Share Improve this question edited May 6, 2015 at 16:12 Huangism 16.4k7 gold badges50 silver badges75 bronze badges asked May 6, 2015 at 16:07 saksak 3,3271 gold badge34 silver badges73 bronze badges2 Answers
Reset to default 2I am doing similar things before.
The way to change the cursor position is using: evt.target.selectionEnd
In your case, you can record down the selectionEnd before inserting, and after inserting, set the selectionEnd to the position it should be.
You can use selectionStart
prop as described here to store and then reset cursor position
var cursorPosition = $('#myTextarea').prop("selectionStart");
Then use something like this to set cursor position
本文标签: javascriptHow to preserve cursor position on textarea text changeStack Overflow
版权声明:本文标题:javascript - How to preserve cursor position on textarea text change? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744674895a2619050.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论