I encountered a very difficult problem today. When I was doing some verification of input boxes, the business logic of my project was that when I selected a specific option of a select, an input input box was displayed for the user to input things. However, if the user did nothing, a warning box must pop up for the user to input. After the input, I would hide the input.
Therefore, the following problem arises. When the input input box is displayed, the focus needs to be automatically obtained. At this time, I use it
The code copy is as follows:
document.getElementById('id').focus();
Well, I tried it and it worked very well. I couldn't help but feel happy and I got it done!
But the calculations are not as good as human calculations. When I was testing with Firefox, it was over. It was easy to use when I first displayed the input, but when I closed the alert reminder box, the input could not get the focus.!
The problem is tricky and I don’t know why. So, I checked the answers of the masters on the Internet, found the following trick, and tried it, and it was really useful!
After alert, the original
The code copy is as follows:
document.getElementByIdx('id').focus();
Change to
The code copy is as follows:
window.setTimeout(function () { document.getElementById('id').focus();}, 0);
Good, problem solved!
setTimeout refers to the execution of the previous expression after delaying the specified time after loading. Of course, here it is the execution of the function after delaying 0ms.
When I just solved this problem, I still don’t know why it can be solved under Firefox. If any great god knows, I will leave a message to let the late students learn it, I am very grateful!