Javascript t=startPos+myValue.lengthmyField.selectionEnd=startPos+myValue.length感谢Rab的回答和@user340140的修复。这里有一个@user340140,您的“丢失插入符号”修复程序,只有在
Javascript t=startPos+myValue.lengthmyField.selectionEnd=startPos+myValue.length感谢Rab的回答和@user340140的修复。这里有一个@user340140,您的“丢失插入符号”修复程序,只有在,javascript,textarea,Javascript,Textarea,t=startPos+myValue.lengthmyField.selectionEnd=startPos+myValue.length感谢Rab的回答和@user340140的修复。这里有一个@user340140,您的“丢失插入符号”修复程序,只有在我将焦点放在您建议的行之前时才有效。似乎不可能更改非焦点字段上的选择,至少在Chrome(当前版本62.0)中,此代码存在一个小问题:selectionStart是一个数值,因此应该与0进行比较,而不是'0',可能应该使用Great!也适用于1
t=startPos+myValue.length代码>
myField.selectionEnd=startPos+myValue.length代码>感谢Rab的回答和@user340140的修复。这里有一个@user340140,您的“丢失插入符号”修复程序,只有在我将焦点放在您建议的行之前时才有效。似乎不可能更改非焦点字段上的选择,至少在Chrome(当前版本62.0)中,此代码存在一个小问题:selectionStart
是一个数值,因此应该与0
进行比较,而不是'0'
,可能应该使用Great!也适用于1.6,只需稍作修改。但不能替换选定的text@mparkuk:它仍然存在用户340140提到的“丢失插入符号位置”问题。(对不起,我应该修好它,但我没时间了。)谢谢你提供了一把工作小提琴。我已经对它进行了更新,同时重置了插入符号的位置,并使其成为一个jquery插件:这是可行的,但光标最终出现在了错误的位置。这将对DOM造成比您需要更多的影响。。将myfield
存储为本地文件对于性能来说要好得多,因为document.getElementById(myfield)
的重复太多了!在顶部执行一次,并使用变量名。您打算连续几次冗余查找同一元素?非常好的扩展!一切正常。谢谢最好的解决方案!谢谢扩展你不拥有的对象的原型不是一个好主意。只需将其设置为常规函数,即可正常工作。这将在设置This.value=…
后清除编辑元素的撤消缓冲区。有办法保存它吗?@fregante那么为什么要有一个原型系统呢。如果您一开始只使用自己的类型,那么就没有必要扩展原型。扩展是原型系统的用途。你没有用>>结束这一行@Phoenix分号在Javascript中是可选的。没有他们也能工作。但是,如果需要,可以使用分号进行编辑。没什么大不了的。它还可以使用版本54.0.2813.0金丝雀(64位)
,基本上是Chrome金丝雀54.0.2813.0。最后,如果希望它按ID插入文本框,请使用document.getElementById('insertyourIDhere')
代替函数中的el
。我的答案的哪一部分不是“纯”JS?我忘了里面有一些C++吗?嘿@ ErikAigner!我的错,我不知道这个问题有两个埃里克的答案。我的意思是埃里克·普金斯基。我将更新答案以更好地反映这一点。虽然这可能回答问题,但最好解释答案的基本部分,以及OPs代码可能存在的问题。这几乎是正确的方法。您链接的文章以包的形式提供了完整的解决方案:。但是我更喜欢execCommand
,因为它支持undo
和made。没有IE支持,但是很小。不幸的是,execCommand
被MDN认为是过时的:我不知道为什么,它似乎真的很有用!是的,execCommand用于其他浏览器,而对于firefox,则使用函数setRangeText。Ramast,这不是您的代码所做的。对于任何定义它的浏览器(most),它将使用setRangeText而不是execCommand。对于您描述的行为,需要首先调用document.execCommand,然后检查返回值。如果为false,请使用target.setRangeText.@Jools如果支持setRangeText,为什么不使用它而不是execCommand?为什么我需要先尝试execCommand?这是一个非常有用的提示,谢谢分享。
function insertAtCursor(myField, myValue) {
//IE support
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
//MOZILLA and others
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ myValue
+ myField.value.substring(endPos, myField.value.length);
} else {
myField.value += myValue;
}
}
$('input[type=button]').on('click', function() {
var cursorPos = $('#text').prop('selectionStart');
var v = $('#text').val();
var textBefore = v.substring(0, cursorPos);
var textAfter = v.substring(cursorPos, v.length);
$('#text').val(textBefore + $(this).val() + textAfter);
});
function insertAtCursor(myField, myValue) {
//IE support
if (document.selection) {
document.getElementById(myField).focus();
sel = document.selection.createRange();
sel.text = myValue;
}
//MOZILLA and others
else if (document.getElementById(myField).selectionStart || document.getElementById(myField).selectionStart == '0') {
var startPos = document.getElementById(myField).selectionStart;
var endPos = document.getElementById(myField).selectionEnd;
document.getElementById(myField).value = document.getElementById(myField).value.substring(0, startPos)
+ myValue
+ document.getElementById(myField).value.substring(endPos, document.getElementById(myField).value.length);
} else {
document.getElementById(myField).value += myValue;
}
}
HTMLTextAreaElement.prototype.insertAtCaret = function (text) {
text = text || '';
if (document.selection) {
// IE
this.focus();
var sel = document.selection.createRange();
sel.text = text;
} else if (this.selectionStart || this.selectionStart === 0) {
// Others
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
this.value = this.value.substring(0, startPos) +
text +
this.value.substring(endPos, this.value.length);
this.selectionStart = startPos + text.length;
this.selectionEnd = startPos + text.length;
} else {
this.value += text;
}
};
function typeInTextarea(el, newText) {
var start = el.prop("selectionStart")
var end = el.prop("selectionEnd")
var text = el.val()
var before = text.substring(0, start)
var after = text.substring(end, text.length)
el.val(before + newText + after)
el[0].selectionStart = el[0].selectionEnd = start + newText.length
el.focus()
}
$("button").on("click", function() {
typeInTextarea($("textarea"), "some text")
return false
})
//Inserts a choicebox selected element into target by id
function insertTag(choicebox,id) {
var ta=document.getElementById(id)
ta.focus()
var ss=ta.selectionStart
var se=ta.selectionEnd
ta.value=ta.value.substring(0,ss)+'<'+choicebox.value+'>'+'</'+choicebox.value+'>'+ta.value.substring(se,ta.value.length)
ta.setSelectionRange(ss+choicebox.value.length+2,ss+choicebox.value.length+2)
}
function insertAtCursor(myField, myValue) {
//IE support
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
// Microsoft Edge
else if(window.navigator.userAgent.indexOf("Edge") > -1) {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)+ myValue
+ myField.value.substring(endPos, myField.value.length);
var pos = startPos + myValue.length;
myField.focus();
myField.setSelectionRange(pos, pos);
}
//MOZILLA and others
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ myValue
+ myField.value.substring(endPos, myField.value.length);
} else {
myField.value += myValue;
}
}
/**
* Usage "foo baz".insertInside(4, 0, "bar ") ==> "foo bar baz"
*/
String.prototype.insertInside = function(start, delCount, newSubStr) {
return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
};
$('textarea').bind("keydown keypress", function (event) {
var val = $(this).val();
var indexOf = $(this).prop('selectionStart');
if(event.which === 13) {
val = val.insertInside(indexOf, 0, "<br>\n");
$(this).val(val);
$(this).focus();
}
})
function insertAtCursor(myField, myValue) {
//IE support
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
// Microsoft Edge
else if(window.navigator.userAgent.indexOf("Edge") > -1) {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)+ myValue
+ myField.value.substring(endPos, myField.value.length);
var pos = startPos + myValue.length;
myField.focus();
myField.setSelectionRange(pos, pos);
}
//MOZILLA and others
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ myValue
+ myField.value.substring(endPos, myField.value.length);
} else {
myField.value += myValue;
}
triggerEvent(myField,'input');
}
function triggerEvent(el, type){
if ('createEvent' in document) {
// modern browsers, IE9+
var e = document.createEvent('HTMLEvents');
e.initEvent(type, false, true);
el.dispatchEvent(e);
} else {
// IE 8
var e = document.createEventObject();
e.eventType = type;
el.fireEvent('on'+e.eventType, e);
}
}
var target = document.getElementById("mytextarea_id")
if (target.setRangeText) {
//if setRangeText function is supported by current browser
target.setRangeText(data)
} else {
target.focus()
document.execCommand('insertText', false /*no UI*/, data);
}
}
function insertAtCaret(text) {
const textarea = document.querySelector('textarea')
textarea.setRangeText(
text,
textarea.selectionStart,
textarea.selectionEnd,
'end'
)
}
setInterval(() => insertAtCaret('Hello'), 3000)
/**
* Inserts the given text at the cursor. If the element contains a selection, the selection
* will be replaced by the text.
*/
export function insertText(input: HTMLTextAreaElement | HTMLInputElement, text: string) {
// Most of the used APIs only work with the field selected
input.focus();
// IE 8-10
if ((document as any).selection) {
const ieRange = (document as any).selection.createRange();
ieRange.text = text;
// Move cursor after the inserted text
ieRange.collapse(false /* to the end */);
ieRange.select();
return;
}
// Webkit + Edge
const isSuccess = document.execCommand("insertText", false, text);
if (!isSuccess) {
const start = input.selectionStart;
const end = input.selectionEnd;
// Firefox (non-standard method)
if (typeof (input as any).setRangeText === "function") {
(input as any).setRangeText(text);
} else {
if (canManipulateViaTextNodes(input)) {
const textNode = document.createTextNode(text);
let node = input.firstChild;
// If textarea is empty, just insert the text
if (!node) {
input.appendChild(textNode);
} else {
// Otherwise we need to find a nodes for start and end
let offset = 0;
let startNode = null;
let endNode = null;
// To make a change we just need a Range, not a Selection
const range = document.createRange();
while (node && (startNode === null || endNode === null)) {
const nodeLength = node.nodeValue.length;
// if start of the selection falls into current node
if (start >= offset && start <= offset + nodeLength) {
range.setStart((startNode = node), start - offset);
}
// if end of the selection falls into current node
if (end >= offset && end <= offset + nodeLength) {
range.setEnd((endNode = node), end - offset);
}
offset += nodeLength;
node = node.nextSibling;
}
// If there is some text selected, remove it as we should replace it
if (start !== end) {
range.deleteContents();
}
// Finally insert a new node. The browser will automatically
// split start and end nodes into two if necessary
range.insertNode(textNode);
}
} else {
// For the text input the only way is to replace the whole value :(
const value = input.value;
input.value = value.slice(0, start) + text + value.slice(end);
}
}
// Correct the cursor position to be at the end of the insertion
input.setSelectionRange(start + text.length, start + text.length);
// Notify any possible listeners of the change
const e = document.createEvent("UIEvent");
e.initEvent("input", true, false);
input.dispatchEvent(e);
}
}
function canManipulateViaTextNodes(input: HTMLTextAreaElement | HTMLInputElement) {
if (input.nodeName !== "TEXTAREA") {
return false;
}
let browserSupportsTextareaTextNodes;
if (typeof browserSupportsTextareaTextNodes === "undefined") {
const textarea = document.createElement("textarea");
textarea.value = "1";
browserSupportsTextareaTextNodes = !!textarea.firstChild;
}
return browserSupportsTextareaTextNodes;
}