自定义在字符串中键入光标

时间:2013-09-03 21:12:34

标签: javascript html string

我希望在替换字符串中更改写入光标(在键入显示/隐藏光标时)。

这是我的字符串:

if(str.indexOf('<html>') != -1){
    str = str.replace(/\<html\>([a-z|A-Z|0-9| ])/g, "<html>\n   \n</html>");
}

这意味着当我输入<html>时,结果为:

<html>

</html>|
       ^
The typing cursor

现在想要的结果:

<html>
|
</html>

如何在替换字符串中自定义/放置光标?

1 个答案:

答案 0 :(得分:0)

单击[提问]:

后,在stackoverflow上的JS控制台中尝试此操作
document.querySelector('textarea#wmd-input').value = "Here >< is your caret"
document.querySelector('textarea#wmd-input').selectionStart = 6
document.querySelector('textarea#wmd-input').selectionEnd = 6

对于textarea以外的一些元素类型

element.setSelection(startPosition, startPosition)

可能有用。