简体   繁体   English

即使单击外部的按钮,如何保持输入的焦点

[英]How do I keep an input focused even when I click a button outside it

Let's say I have an input假设我有一个输入

<input type="text" id="inPut" autofocus>

and a button和一个按钮

<button id="btn">Some text</button>

I want that onblur, it loses focus (as it normally would), but when I click this button, nothing happens to the focus ie it does not lose focus我想要那个onblur,它失去焦点(就像通常那样),但是当我点击这个按钮时,焦点没有任何反应,即它不会失去焦点

You can use JS to focus the input on button click.您可以使用 JS 将输入集中在按钮单击上。

 const btn = document.querySelector("#btn"); const inp = document.querySelector("#inp"); btn.addEventListener("click", () => { inp.focus(); });
 <input id="inp" type="text"> <button id="btn">Click</button>

If you don't want the input to focus on click if it is not already focused.如果您不希望输入集中在单击上(如果它尚未集中)。

You can store input's focus information in a variable, toggle that variable on button's mouseover event (this would work because mouseover fires before click and mouseover doesn't make the button active)您可以将输入的focus信息存储在变量中,在按钮的mouseover事件上切换该变量(这会起作用,因为mouseoverclick之前触发并且mouseover不会使按钮处于活动状态)

 const btn = document.querySelector("#btn"); const inp = document.querySelector("#inp"); let isInputFocused = false; btn.addEventListener("mouseover", () => { if (inp === document.activeElement) { isInputFocused = true; } else { isInputFocused = false; } }); btn.addEventListener("click", () => { if (isInputFocused) { inp.focus() } });
 <input id="inp" type="text"> <button id="btn">Click</button>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我怎样才能制作一个按钮保持聚焦的CSS样式,直到我再次点击它 - How can I make a button keep the focused css style till I click on it again 使用jQuery,当我在输入框之外单击时如何更改输入元素的值? - Using jQuery, how do I change the input element's value when I click outside of the input box? 在 Vue 3 中单击按钮而不闪烁后,如何将注意力集中在输入上? - How do I keep the focus on an input, after i click on a button without flickering in Vue 3? 即使刷新页面后,如何使按钮保持禁用状态? - How do i keep the button disabled even after the refresh of the page? 带有文本标签的按钮:即使在文本标签上方,如何保持悬停颜色? - Button with text label: How do I keep the hover color even when over text label? 空格并输入“点击”关注的输入。 如何禁用此行为? - Space and enter “click” on the input that's focused. How do I disable this behavior? 单击外部时如何隐藏菜单? - How do I hide the menu when I click outside? 当我在“选择文件”之外单击时,输入文件正在打开,如何仅在单击了实际的“按钮”后才能打开它? - My input file is opening when I click outside of “choose file”, how can I make it only open if the actual “button” is clicked? 如何单击下载页面 chrome 中的保留按钮 - how do I click a keep button in download page chrome 当我单独单击带有 JavaScript 的按钮时,如何聚焦输入 - How do I focus an input when I click a button with JavaScript alone
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM