Keep <div> and its children in focus until focus out of <div>

半腔热情 提交于 2019-12-05 20:28:33

Okay, I think that this is what you want:

Demo: http://jsfiddle.net/SO_AMK/GNfzw/

HTML:

<div>
    <input type='text'>
    <span></span>
</div>

<div>
    <input type='text'>
    <span></span>
</div>

<div>
    <input type='text'>
    <span></span>
</div>

CSS:

div {
    margin: 20px;
    padding: 10px;
    outline: 0;
}

jQuery:

$(function() {
    $('div input').parent().attr("tabindex",-1).focus( function() {
        $(this).css('background','#eee');
        $(this).find('span').text(' triggered');

        $(this).focusout(function() {
            $(this).children('span').empty();
            $(this).css('background','white');

        });            

   });
    $('div input').focus( function() {
        $(this).parent().css('background','#eee');
        $(this).siblings('span').text(' triggered');

        $(this).parent().focusout(function() {
            $(this).children('span').empty();
            $(this).css('background','white');

        });            

   });

});

It could probably be more efficient but it seems to work.

This is a bit of a more literal approach than the other answer, but for completeness seems relevant as it does one more thing: Autofocus back to the input. It could be useful, although the other answer is probably easy enough.

$(function() {
    var $divs = $('div'),
        $entered = null;

    var on = function() {
        var $target = $(this);

        _off();

        $entered = $target.parent().addClass('on');
        $target.siblings('span').text(' triggered');
    };

    var focus = function(){
        $(this).find('input').focus();
    };

    var off = function() {
        if ($entered !== null && $(this).parent().is($entered)) {
            return;
        }

        _off();
    };

    var _off = function(){
        $divs.removeClass('on').children('span').text('');
    };

    var entered = function(e){
        if (e.type == 'mouseenter') {
            $entered = $(this);
        } else {
            $entered = null;
        }
    };

    $divs.find('input').focus(on).blur(off);

    $divs
        .attr('tabindex', -1)
        .bind('mouseenter mouseleave', entered)
        .bind('focus', focus);
});

http://jsfiddle.net/userdude/34HLU/2/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!