如何在textarea文本更改时保留光标位置?

时间:2015-05-06 16:07:38

标签: javascript jquery reactjs

我正在尝试实现一个textarea,它自动在React中插入紧密的parens,但每当我修改textarea的value属性时,光标会跳转到正在编辑的文本的末尾。

这是我的onChange函数:

    //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}})

    }

这成功插入了paren,但如何保留光标位置?

2 个答案:

答案 0 :(得分:2)

我之前做过类似的事情。

更改光标位置的方法是使用:evt.target.selectionEnd

在您的情况下,您可以在插入之前记录selectionEnd,插入之后,将selectionEnd设置为它应该的位置。

答案 1 :(得分:1)

您可以使用here所述的selectionStart道具来存储然后重置光标位置

var cursorPosition = $('#myTextarea').prop("selectionStart");

然后使用this之类的东西来设置光标位置