在文本中的光标位置后面插入文本
下面的脚本将文本插入到文本区域的末尾。我需要更改为 在文本区域中当前光标位置之后插入文本。在文本中的光标位置后面插入文本
jQuery(document).ready(function($){
$('#addCommentImage').click(function(){
var imageLoc = prompt('Enter the Image URL:');
if (imageLoc) {
$('#comment').val($('#comment').val() + '[img]' + imageLoc + '[/img]');
}
return false;
});
});
您可以结帐this answer。该insertAtCaret
jquery插件似乎非常好。
实际上链接到一个无功能的版本。上面那个是你想要的。这里是小提琴http://jsfiddle.net/rmDzu/2/ – John 2014-03-07 12:19:59
我已经修改了这些的各种版本,以提出一个版本,将第一个文本放置在所选内容之前,第二个文本放在所选内容之后并保留所选内容。这工作在铬和FF,而不是在IE中。
jQuery.fn.extend({
insertAtCaret: function(myValue, myValueE){
return this.each(function(i) {
if (document.selection) {
//For browsers like Internet Explorer
this.focus();
sel = document.selection.createRange();
sel.text = myValue + myValueE;
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(startPos,endPos)+myValueE+this.value.substring(endPos,this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = ((startPos + myValue.length) + this.value.substring(startPos,endPos).length);
this.scrollTop = scrollTop;
} else {
this.value += myValue;
this.focus();
}
})
}
});
用法: $('#box').insertAtCaret("[Before selection]", "[after]");
另外:不以任何方式声称这是我的。
如果上述不起作用(它没有我的情况下 - 也许我的配置是有点不同),这里是另一种解决方案:
你可以使用这个扩展功能获得位置:
(function ($, undefined) {
$.fn.getCursorPosition = function() {
var el = $(this).get(0);
var pos = 0;
if ('selectionStart' in el) {
pos = el.selectionStart;
} else if ('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
return pos;
}
})(jQuery);
的用法是:
var content = $('#selector').val();
var newContent = content.substr(0, position) + "text to insert" + content.substr(position);
$('#selector').val(newContent);
01:
var position = $("#selector").getCursorPosition()
在位置插入文本
就是这样。
谢谢,对Angular JS实现非常有用,因为在ng模型绑定的情况下insertAtCaret()修改不起作用。 – Denis 2014-07-13 17:33:15
很适合在光标位置插入文本。请注意,如果用户选择了一些文本,它将在选择之前插入,而不是替换它(在Chrome中进行测试)。 – rybo111 2015-11-29 12:20:03
function getCursorPosition will change to'document.getElementById('textarea')。selectionStart;'或'document.getElementById('textarea')。selectionEnd;' – 2016-06-13 19:40:35
[插入文本到jQuery的文本到textarea](http://stackoverflow.com/questions/946534/insert-text-into-textarea-with-jquery) – bummi 2013-12-02 14:36:14