单击DIV中的元素时,DIV失去了焦点 [英] DIV losing focus when clicking on elements inside it

查看:186
本文介绍了单击DIV中的元素时,DIV失去了焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我单击DIV中的元素时,为什么DIV会失去焦点? 我有一个JS,它在失去焦点时会隐藏DIV.但这在单击DIV中的元素时不会发生. 需要使用.on来完成,因为正在进行一些ajax加载.

Why does the DIV lose focus when i click on elements inside it? I have an JS that hides the DIV when it loses focus. But that should not happen when clicking on elements inside the DIV. It needs to be done with .on because there is some ajax loading going on.

$(document).on('focusout', '#geomodal', function(e) {
    console.log('.focusout');
});

<div id="geomodal" tabindex="-1">
    <input value="109" name="districts[]" type="checkbox">
    <label>Bla</label>
    <br>
    <input value="152673" name="districts[]" type="checkbox">
    <label>Blabla</label>
    <br>
</div>

http://jsfiddle.net/2g41su81/2/

jQuery文档:

focusout事件在元素或任何元素发送到该元素时 里面失去焦点.

The focusout event is sent to an element when it, or any element inside of it, loses focus.

推荐答案

一次只有一个元素具有焦点-如果输入具有焦点,则div不会.失去焦点后,请检查新聚焦的元素是您的div还是孩子,并且在这种情况下不要将其隐藏.

Only one element has focus at a time - if an input has focus, your div doesn't. After losing focus, check if the newly-focused element is your div or a child, and don't hide it in that case.

$(document).on('focusout', '#geomodal', function (e) {
    setTimeout(function(){
        var focus=$(document.activeElement);
        if (focus.is("#geomodal") || $('#geomodal').has(focus).length) {
            console.log("still focused");
        } else {
            console.log(".focusout");
        }
    },0);
});

setTimeout对于使新元素在进行检查之前获得焦点是必需的.

The setTimeout is necessary to allow the new element to gain focus before doing the check.

http://jsfiddle.net/2g41su81/5/

这篇关于单击DIV中的元素时,DIV失去了焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆