【问题标题】:Keep a text field focused despite clicking elsewhere尽管点击了其他地方,但仍保持文本字段的焦点
【发布时间】:2020-05-19 14:12:27
【问题描述】:

我想保持文本字段的焦点,尽管点击了红色的 div。我尝试了不同的方法,为什么没有任何效果?

function stopEvent(e) {
   e.stopPropagation();
   e.preventDefault();
   return false;    
}
function setFocus(e) {
   document.getElementById("textField").focus();
   stopEvent(e);
}
document.getElementById("textField").focus();
<div onmouseover="setFocus(event);" onfocus="this.blur();">
  <div style="background-color:red; height:100px;" onclick="stopEvent(event)" onfocus="this.blur();">Click area</div>
  <div><input id="textField" type="text" value="focused" /></div>
</div>
  
  

【问题讨论】:

  • 如果您向元素添加 ID,则可以通过 window.textField 引用它。您仍然应该避免在项目中的元素上设置 ID。

标签: javascript html focus


【解决方案1】:

您在单击区域 div 上使用了 stopEvent 而不是 setFocus。此外,您没有在 setFocus 中返回 false,因此在 stopEvent 中返回 false 是无用的。

function stopEvent(e) {
   e.stopPropagation();
   e.preventDefault();
   return false;    
}
function setFocus(e) {
   document.getElementById("textField").focus();
   return stopEvent(e);
}
document.getElementById("textField").focus();
<div onmouseover="setFocus(event);" onfocus="this.blur();">
  <div style="background-color:red; height:100px;" onclick="setFocus(event)" onfocus="this.blur();">Click area</div>
  <div><input id="textField" type="text" value="focused" /></div>
</div>

【讨论】:

  • 如何防止在滚轮点击时也改变焦点?
【解决方案2】:

你可以做到这一点

const field = document.getElementById("textField");

field.addEventListener("blur", function( event ) {
  setTimeout(function () {
      field.focus();
    }, 100);   
}, true);
<div style="background-color:red; height:100px;">Click area</div>
<div><input id="textField" type="text" value="focused" /></div>

【讨论】:

    【解决方案3】:

    如果您希望它始终保持专注,只需添加 document.getElementById("textField").addEventListener('blur',() =&gt; document.getElementById("textField").focus())

    document.getElementById("textField").focus();
    document.getElementById("textField").addEventListener('blur',() => 
    document.getElementById("textField").focus())
    <div>
      <div style="background-color:red; height:100px;">Click area</div>
      <div><input id="textField" type="text" value="focused" /></div>
    </div>

    如果您想在点击红色 div 时重新聚焦,而不仅仅是将 'click' 事件侦听器添加到 redDiv。

    window.textField.focus();
    window.redBox.addEventListener('click',() => window.textField.focus())
    <div>
      <div id="redBox" style="background-color:red; height:100px;">Click area</div>
      <div><input id="textField" type="text" value="focused" /></div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-25
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      • 2017-05-13
      • 1970-01-01
      • 2020-03-18
      • 1970-01-01
      相关资源
      最近更新 更多