简体   繁体   中英

Set focus on textfield when un-focused

I want a text field to always be focused. When they click out of the textfield, I want the focus to go back into the textfield.

How would I accomplish this with jquery?

$('input').focus();

$('input').**unfocused?**( function($) { $('input').focus();} );

您正在寻找blur事件

$(':text').blur(function() { this.focus(); });

The following code is an alternative solution which depends on periodically checking the control's state.

var controlFocus=false;
$("#txtName").focus(function(){
    $(this).addClass("focused"); 
    if(!controlFocus) {
        controlFocus = true;
        setInterval(function(){ 
            var o = $("#txtName");
            if(!o.hasClass("focused")) o.focus();
        }), 200);
    }
}).blur(function(){$(this).removeClass("focused");});

After the textbox (named txtName) gets its first focus, every 0.2 second, the code controls whether the textbox has focus. If it doesn't, it's focused. But this can be a really annoying thing.

Bind to get the change event, and check if focus must be forced to this input if so, insert some data in the document. $(document).data('_force_focus', e.target)

$('input.force').bind('change', function(e) {
        if( need_force_focus() ) {
                $(document).data('_force_focus', e.target);
        } else {
                $(document).removeData('_force_focus');
        }
   });

Now on the document bind to the focusin event, testing if document have the “_force_focus” data. If so set the focus to the value. It's important prevent the focusin retrigger by testing against e.target

$(document).bind('focusin', function (e) {
     var t = $.data(document, '_force_focus');
             if( t && e.target !== t ) {
                     $(t).trigger('focus');
                     return false;
             }
             return true;
     });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM