【发布时间】:2021-10-20 00:44:51
【问题描述】:
如何在单击按钮向(以前的)活动输入文本框添加内容之前选择多个输入元素之一?有什么方法document.hadFocus吗?我可以使用onFocusOut 获取输入的 id 并将其传递给我的函数吗?
我在 JQuery 中看到了很多解决方案,但任何人都可以在 vanilla JS 中做到这一点吗?
function insertAtCursor(newText, el = document.activeElement) {
//getElementsByTagName("input")[0].focus();
const start = el.selectionStart;
const end = el.selectionEnd;
const text = el.value;
const before = text.substring(0, start);
const after = text.substring(end, text.length);
el.value = (before + newText + after);
el.selectionStart = el.selectionEnd = start + newText.length;
el.focus();
}
【问题讨论】:
-
这个答案可能会有所帮助:stackoverflow.com/a/68176703/11711316
-
感谢@Cuong,这看起来很完美......如果我知道 JQ。我正在寻找香草 JS 中的解决方案。
-
我的想法是您可以创建一个变量来存储最新的文本框并在文本框被聚焦时更新它。你只需要使用js来绑定焦点事件而不是jquery。
标签: javascript css-selectors pseudo-element