Home > Web Front-end > JS Tutorial > Solution to the problem that focus cannot obtain focus after jquery blur

Solution to the problem that focus cannot obtain focus after jquery blur

黄舟
Release: 2017-06-27 11:42:50
Original
1577 people have browsed it

1: Many children's shoes may encounter this situation: after

jquery's blur, focus cannot get focus.

2: Usage scenario:

When the user fills in the information, if the email address is empty, it will prompt you to fill in the email address and place the cursor in the text box for filling in the email address to facilitate the user to fill in the email address again. enter.

Of course we will use jquey's blur() and focus() two functions to achieve the above requirements:

$("#email").blur(function(){       if($("#email").val()==''){
            alert('请填写您的邮箱');
            $("#email").focus();    
       }    
})
Copy after login

Three: Code explanation:

When the text box for filling in the email loses focus, if the filled in email address is empty, the prompt 'Please fill in your email' will pop up and regain the focus of the text box to facilitate the user to re-enter.

After running test.html on FF: you will find that the pop-up box pops up, but it cannot get the focus. It is very strange. There is obviously no error in the code. The running result on IE is normal. Both the pop-up information and the focus will be obtained.

Four: Then you will definitely think that this is another compatibility issue.

Yes. FF and IE have indeed caused us a lot of trouble in terms of compatibility.

5: The reason for the problem should be that the blur and focus mechanisms of FF and IE are different.

FF's focus can only be before blur.

6: So how to solve this bug?

Use settimeout to make a delay.

Modify the code as follows:

$("#email").blur(function(){    if($("#email").val()==''){
        alert('请填写您的邮箱');        //$("#email").focus();
        window.setTimeout (function(){ document.getElementById ('email'). select();},0 );     
    }    
})
Copy after login

Seven: Run on IE and FF respectively, perfectly compatible.

The above is the detailed content of Solution to the problem that focus cannot obtain focus after jquery blur. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template