javascript - 尽管单击其他地方,但仍保持文本字段的焦点
问题描述
尽管单击了红色 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>
解决方案
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>
推荐阅读
- svg - 如何在不使用 viewBox 的情况下消除 SVG 符号周围的间隙
- laravel - 我如何调试这个“找不到类'应用程序/地址'”?
- html - 如何防止谷歌在站点链接中放置材料图标文本?
- javascript - 如何将 jQuery 信息添加到 html 表单?
- c++ - 在完成对 k 个已排序流进行排序的功能时需要帮助
- r - 如何检查数据表中每一行的列值是否在另外两个的范围内
- python - 生成带有括号和被置换的运算符的字符串列表的所有组合
- javascript - 在 React 构造函数中未调用 Console.Log
- javascript - 如何在 LocalStorage 中“保存”我的 JS 更改
- javascript - AngularJs - 以编程方式提交表单