如何使用jquery从指针的当前位置向文本框添加文本? [英] How to add a text to a textbox from the current position of the pointer with jquery?
本文介绍了如何使用jquery从指针的当前位置向文本框添加文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含一些单词和文本的文本框,我要做的事情是,当用户单击按钮时,从指针的当前位置向文本框的文本添加一些单词. ? 这是文本框和按钮:
<textarea id="txt" rows="15" cols="70">There is some text here.</textarea>
<input type="button" id="btn" value="OK" />
解决方案
很巧合,我只是回答了类似的工作演示 >
I have a textbox with some words and text.The thing I want to do is this that when the user clicks on a button add some words to the text of the textbox from the current position of the pointer.How to do this? This is the textbox and the button:
<textarea id="txt" rows="15" cols="70">There is some text here.</textarea>
<input type="button" id="btn" value="OK" />
解决方案
Quite coincident, I just answer a similar question a few minutes ago. You can use a custom function like this:
jQuery.fn.extend({
insertAtCaret: function(myValue){
return this.each(function(i) {
if (document.selection) {
//For browsers like Internet Explorer
this.focus();
sel = document.selection.createRange();
sel.text = myValue;
this.focus();
}
else if (this.selectionStart || this.selectionStart == '0') {
//For browsers like Firefox and Webkit based
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = startPos + myValue.length;
this.scrollTop = scrollTop;
} else {
this.value += myValue;
this.focus();
}
})
}
});
Basically, this plugin allows you to insert a piece of text at caret of multiple textbox
or textarea
. You can use it like this:
$('#element1, #element2, #element3, .class-of-elements').insertAtCaret('text');
这篇关于如何使用jquery从指针的当前位置向文本框添加文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文