javascript 如何使用Javascript在光标位置的TextArea中附加文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7469420/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to append text in TextArea at cursor location using Javascript
提问by
I have a TextArea, textBox and a button. TextArea has some text e.g This is a cat.
我有一个 TextArea、textBox 和一个按钮。TextArea 有一些文字,例如This is a cat。
Now my requirement is If someone set cursor position in TextArea and enter text in textbox and click on button the text should be append in cursor position instead of last. e.g.
现在我的要求是如果有人在 TextArea 中设置光标位置并在文本框中输入文本并单击按钮,则文本应附加在光标位置而不是最后一个。例如
TextArea: This is a cat. Cursor position: after "a" Entered Text in TextBox: black
TextArea:这是一只猫。光标位置:在“a”之后在文本框中输入文本:黑色
Output: This is a black cat.
输出:这是一只黑猫。
How can I do this using javascript.
我怎样才能使用 javascript 做到这一点。
Thanks in advance.
提前致谢。
采纳答案by Tim Down
I've answered this before:
我以前回答过这个:
Inserting text at cursor in a textarea, with Javascript
使用 Javascript 在 textarea 中的光标处插入文本
One extra note is that IE will lose the caret position by the time a click event fires on a button. To get round this you can either use themousedown
event instead, or make the button unselectable by adding an unselectable="on"
attribute.
一个额外的注意事项是当点击事件触发按钮时,IE 将丢失插入符号位置。为了解决这个问题,您可以改用mousedown
事件,或者通过添加unselectable="on"
属性使按钮不可选择。
回答by joostdevries
Using Google
: How do I add text to a textarea at the cursor location using javascript
使用Google
:如何使用 javascript 将文本添加到光标位置处的文本区域
Copy the code from the above post (The one by Tim Down) and replace
复制上面帖子中的代码(Tim Down 的那个)并替换
insertTextAtCaret(textarea, "[INSERTED]");
with
和
var textBox = document.getElementById("your-textbox-name");
insertTextAtCaret(textarea, textbox.value);