1. Set the element to gain focus to listen for keyboard events The biggest advantage of element focus is that it allows keyboard events to be sent. Many HTML elements are focusable by default, such as form elements, a anchor links, etc. But most of them cannot be focused by default. To make an element focusable, it can be implemented in HTML code or JavaScript script.
html:
JavaScript:
oDiv.tabIndex = 0;
where tabIndex is The navigation order of the TAB key, which can be positive, negative or zero.
When an element gets focus, there will be a border indication. If you want not to display this border, you can
html:
JavaScript:
oDiv. hideFocus = 'on';
2. The element is clearly focused but has no effect Sometimes the focus of an element is set using JavaScript, but the focus does not fall on the element in the end, which is really confusing. Its solution.
The problem is that if you focus on other elements in the event handler of the focusable element, the focus may not be achieved, because if the event is a focusable event, such as mouse, keydow (keypress), etc., in these events Focusing other elements directly within the handler function will fail.
oDiv.onmousedown = function(){
document .getElementById('ipt').focus();
};
Refer to the browser kernel processing flow chart:
When the browser reflows for the first time After reflow, the focus stops on another element, but after the reflow returns, the default operation after event processing will continue to be performed, that is, focusing on the event source, which is the mousedown element. At this time, the second reflow is triggered. After the reflow The focus is on the element. So the focus in the event handler function becomes invalid.
Is there a solution? The answer is yes. As can be seen from the picture, just put the focus after the second Reflow. Just execute it. This can be delayed by using the setTimeout method and then put into the queue and then executed. Because due to the single-threaded nature of the JavaScript engine, the entire process in the figure is executed continuously. During this process, the JS engine has never been idle. After all the above operations are completed, the scheduled callback has a chance to be executed. So you can:
oDiv.onmousedown = function(){
setTimeout(function(){
document.getElementById('ipt').focus();
}, 0);
};
From the above, it doesn’t matter even if the last millisecond is set to 0.
3. An exception is thrown when focusing
In IE, when If the element is invisible, if it is focused, an exception will be thrown, because in many applications we often focus without testing whether the element is invisible, because even so there is no problem (who said that invisible elements cannot be focused? ?)..So, you can use try{}catch(){} to ignore this exception under IE.
try{
element.focus();
}catch(e){}
This is it, related to JavaScript focus capture The discussion of the issue is completed.