【问题标题】:How to select the previously "current active" element? Is there document.hadFocus?如何选择以前的“当前活动”元素?有没有document.hadFocus?
【发布时间】: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


【解决方案1】:

我通过替换 buttononclick eventListener 解决了这个问题(用于向输入框添加文本...)
在前一个元素(输入框)上带有 focusout eventlistener
这样,事件就绑定到输入框并拥有我需要的一切。
e.relatedTarget 与我需要的相反(“hadFocus”)。它是“什么元素(如果有的话)正在成为这个focusout 事件的新焦点?” if 语句使用此 relatedTarget 来确保按钮失去焦点。
this 与按下按钮时“hadFocus”的 inputBox 相关联。

inputBox.addEventListener( "focusout", insertAtCursor )
function insertAtCursor( event ){
    if ( e.relatedTarget?.parentElement?.classList?.value == "buttonSet" ){
      const text    = this.value;                
      const start   = this.selectionStart;       
      const end     = this.selectionEnd;         
      const wordId  = this.id;                   
      const newTextToAddFromButton = e.relatedTarget.innerText;
      ...
     }
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-27
    • 2016-02-27
    • 2017-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多