javascript - 焦点事件被另一个焦点事件忽略

标签 javascript jquery

在下面的代码中,如果文本框获得焦点,则会出现 redDiv。

如果 redDiv 或其子级处于焦点中,那么它必须保持可见,并且仅在失去焦点时才隐藏。你能帮忙吗?

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>

    <script src="jquery-1.8.2.min.js"></script>

    <script type="text/javascript">


        $(document).ready(function () {

            var onetxt = $('<input type="text" />');

            var Input1 = $('<input type="text" />');

            var redDiv = $('<div>', { tabindex: "5", style: "width:200px;height:200px;background:red; display:none;", text: 'test', html:"<br /><br />" }).append(Input1);





            onetxt.focusin(function () {
                redDiv.show();
            });
            Input1.focusin(function () {
                redDiv.show();
            });
            redDiv.focusin(function () {
                redDiv.show();
            });


            onetxt.blur(function () {
                redDiv.hide();
            });






            $('#myarea').after(onetxt,redDiv);

        });



    </script>

</head>
<body>

    <div id="myarea"></div>

</body>
</html>

最佳答案

每次隐藏 div 时,您都需要检查是否满足您的条件。

例如(我还设置了 10 毫秒的超时,以允许焦点在元素隐藏之前切换):

$(document).ready(function () {
    var hider = null;
    var onetxt = $('<input type="text" />');
    var Input1 = $('<input type="text" />');
    var redDiv = $('<div>', {
        tabindex: "5",
        style: "width:200px;height:200px;background:red; display:none;",
        text: 'test',
        html: "<br /><br />"
    }).append(Input1);

   function hideRed () {
       if (!onetxt.is(':focus') && !Input1.is(':focus') && !redDiv.is(':focus')) {
           hider = setTimeout(function () {redDiv.hide();}, 10);
       }
    }

    function showRed () {
        if (hider !== null) {
            clearTimeout(hider);
            hider = null;
        }
        redDiv.show();
    }

    onetxt.focusin(showRed);
    Input1.focusin(showRed);
    redDiv.focusin(showRed);

    redDiv.blur(hideRed);
    Input1.blur(hideRed);
    onetxt.blur(hideRed);

    $('#myarea').after(onetxt, redDiv);
});

Jsfiddle

关于javascript - 焦点事件被另一个焦点事件忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19247136/

相关文章:

javascript - 在公共(public) channel discord.js 中发送私有(private)消息

javascript 函数在 localhost 上工作但在 iis 上不起作用

Jquery如何从选中的复选框中获取数组

jquery - 如果文件在 jquery 中上传不起作用,则获取文件名

javascript - 使用 Javascript 将类添加到动态行

javascript - 将 cookie 从 Controller 传递到 Laravel 中的 View

javascript - 想在 jquery 中旋转元素

javascript - Div 调整大小在 Internet Explorer 上不起作用

javascript - 如何将隐藏的 Canvas 对象复制到图像而不使图像模糊

javascript - 如何使用 JQuery 中的 data 参数解析 JSON?