Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

javascript - Maintain focus on an input tag

I'm trying to keep focus on an input element with this code:

<input onblur="this.focus()" />

But it doesn't seem to work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If we just call .focus() right on blur event, it will restore focus, but actually there will be no text cursor. To handle this we have to let element to lose focus and then return it in few milliseconds. We can use setTimeout() for this.

$('#inp').on('blur',function () { 
    var blurEl = $(this); 
    setTimeout(function() {
        blurEl.focus()
    }, 10);
});

Here's working example. Be careful - you can't leave text field after you enter it =)

EDIT I used jQuery, but it can be easily done without it.
EDIT2 Here's pure JS version fiddle

<input type="text" id="elemID" />

<script type="text/javascript">
    document.getElementById('elemID').onblur = function (event) { 
        var blurEl = this; 
        setTimeout(function() {
            blurEl.focus()
        }, 10);
    };
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...