除非使用jQuery单击特定元素,否则对模糊执行操作 [英] Action on blur except when specific element clicked with jQuery

查看:70
本文介绍了除非使用jQuery单击特定元素,否则对模糊执行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两个元素在起作用:

$('#myInput') // an input field for search
$('#myList') // a list to display search results

我想要隐藏当输入不再具有焦点时的列表,如下所示:

I want to hide the list when the input no longer has focus, like so:

$('#myInput').blur(function() {
  $('#myList').hide();
});

除非单击列表项,否则此工作正常,因为模糊事件会触发并隐藏列表在点击注册之前。目标是当列表的任何部分被点击时列表保持可见,即使这会导致输入模糊。

This works great, except when a list item is clicked, because the blur event fires and hides the list before the click is registered. The goal is for the list to stay visible when any part of the list is clicked, even though this will cause the input to blur.

我该怎么做?谢谢!

推荐答案

您可以通过保持全局变量和setTimouts等待延迟200毫秒然后检查是否可以实现此目的2个元素中的一个具有焦点。

You can accomplish this by keeping a global variable, and setTimouts, to wait a delay of 200ms and then check if one of the 2 elements have focus.

var keepFocus = false;

function hideList(){
    if(!keepFocus){
        $('#myList').hide();
    }
}

$('#myInput').blur(function() {
    keepFocus = false;
    window.setTimeout(hideList, 200);
}).focus(function(){
    keepFocus = true;
});


$('#myList').blur(function() {
    keepFocus = false;
    window.setTimeout(hideList, 200);
}).focus(function(){
    keepFocus = true;
});

这篇关于除非使用jQuery单击特定元素,否则对模糊执行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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