javascript 按下按钮时如何使元素不失去焦点?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12154954/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make element not lose focus when button is pressed?
提问by Lucas
I have a textarea in which I am inserting content at the location of the caret (thanks to Tim Down's answer). It inserts the content when the user presses a button. But it seems that when the button is pressed, the focus on the textarea is lost. How do I keep the focus there, providing the location of the caret is also the same? I was thinking along the lines of using evt.preventDefault()
with .focusout()
. If that helps.
我有一个文本区域,在其中我在插入符号的位置插入内容(感谢Tim Down 的回答)。它在用户按下按钮时插入内容。但似乎当按下按钮时,textarea 上的焦点丢失了。如果插入符号的位置也相同,我如何将焦点保持在那里?我正在考虑使用evt.preventDefault()
with .focusout()
。如果那有帮助。
采纳答案by jfriend00
You can't stop the focus from moving to a focusable element and still allow the mouse click to have its normal behavior (such as click
the button). If you click on an element that supports focus such as a button, it will get the keyboard focus.
您无法阻止焦点移动到可聚焦元素,而仍然允许鼠标单击具有其正常行为(例如click
按钮)。如果单击按钮等支持焦点的元素,它将获得键盘焦点。
It is possible to programmatically put focus back on an element if done properly. If done poorly, it can ruin the usability of a page.
如果操作得当,可以以编程方式将焦点重新放在元素上。如果做得不好,它可能会破坏页面的可用性。
Demo: JSFiddle
演示:JSFiddle
回答by Thomas Deutsch
There is no need to renew the focus!
有没有必要更新的焦点!
Simply make sure you handle the mousedown event. The mousedown event will fire before the focus of another element is lost.
只需确保您处理 mousedown 事件。mousedown 事件将在另一个元素的焦点丢失之前触发。
In your mousedown event handler, you need to to prevent event default behavior.
在您的 mousedown 事件处理程序中,您需要防止事件默认行为。
e.preventDefault(); // on your mousedown event
回答by Tmthetom
You have to renew focus when button is pressed.
按下按钮时,您必须更新焦点。
HTML code:
HTML代码:
<input id="messageBox" autofocus />
<input type="button" id="messageSend" onclick="setFocusToMessageBox()" value="Send" />
Javascript code:
Javascript代码:
<script>
function setFocusToMessageBox(){
document.getElementById("messageBox").focus();
}
</script>
回答by Shiv Kumar Ganesh
You can easily do this by applying focus back to the text area programmatically as the button click function is over. This way you can regain the focus along with the click event each time.
您可以通过在按钮单击功能结束时以编程方式将焦点重新应用到文本区域来轻松完成此操作。通过这种方式,您可以在每次单击事件的同时重新获得焦点。