首页 > 解决方案 > 尽管单击其他地方,但仍保持文本字段的焦点

问题描述

尽管单击了红色 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>
  
  

标签: javascripthtmlfocus

解决方案


document.getElementById("textField").addEventListener('blur',() => 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 时重新聚焦,而不仅仅是向 redDiv 添加 'click' 事件侦听器。

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>


推荐阅读