如何使用JQuery InsertAtCaret函数 [英] How to use JQuery InsertAtCaret Function
问题描述
我找到了JQuery InsertAtCaret函数这里但是没有详细说明如何使用它。我已经尝试了很多东西,以了解如何使用它,但找不到任何方法。这是函数。
I have found JQuery InsertAtCaret Function Here But there is no detail given how to use it. I have tried a lot to understand that how it can be used, but could not find any way. Here is the function.
$.fn.insertAtCaret = function(myValue) {
return this.each(function() {
var me = this;
if (document.selection) { // IE
me.focus();
sel = document.selection.createRange();
sel.text = myValue;
me.focus();
} else if (me.selectionStart || me.selectionStart == '0') { // Real browsers
var startPos = me.selectionStart, endPos = me.selectionEnd, scrollTop = me.scrollTop;
me.value = me.value.substring(0, startPos) + myValue + me.value.substring(endPos, me.value.length);
me.focus();
me.selectionStart = startPos + myValue.length;
me.selectionEnd = startPos + myValue.length;
me.scrollTop = scrollTop;
} else {
me.value += myValue;
me.focus();
}
});
};
我有一个文本框输入字段和一个textarea。我应该在哪里调用此函数,我应该给它什么值。而且我必须提供我的textarea的引用。
I have a textbox input field and a textarea below it. Where Should I call this function and what value should I give it. And Where I have to give the reference of my textarea.
推荐答案
以下是上述插件的修改版本:
Here is modified version of above plugin:
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();
}
})
}
});
基本上,这个插件允许你在多个 textbox
或 textarea
。您可以像这样使用它:
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 InsertAtCaret函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!