[英]How to make element not lose focus when button is pressed?
I have a textarea in which I am inserting content at the location of the caret (thanks to Tim Down's answer ).我有一个 textarea,我在插入符号的位置插入内容(感谢Tim Down 的回答)。 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.
但似乎按下按钮时,textarea 上的焦点丢失了。 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()
.我正在考虑将
evt.preventDefault()
与.focusout()
。 If that helps.如果那有帮助。
There is no need to renew the focus !没有必要更新焦点!
Make sure you handle the mousedown event (instead of the click-event).确保您处理 mousedown 事件(而不是单击事件)。 The mousedown event will fire before the focus of another element is lost.
mousedown 事件将在另一个元素的焦点丢失之前触发。
In your mousedown event handler, you need to to prevent event default behavior.在您的mousedown事件处理程序中,您需要防止事件默认行为。
e.preventDefault(); // on your mousedown event
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).您无法阻止焦点移动到可聚焦元素,并且仍然允许鼠标单击具有其正常行为(例如
click
按钮)。 If you click on an element that supports focus such as a button, it will get the keyboard focus.如果单击支持焦点的元素(例如按钮),它将获得键盘焦点。
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.
如果做得不好,它可能会破坏页面的可用性。
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>
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.
通过这种方式,您可以在每次单击事件的同时重新获得焦点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.