【问题标题】:Force focus on one element with an exception. (jQuery)强制关注一个元素,但有例外。 (jQuery)
【发布时间】:2011-03-14 20:39:39
【问题描述】:

我有两个输入字段。无论用户在哪里点击除非它在#input 上,我都想强制关注#area。我尝试过类似的方法,但由于输入是文档的一部分,因此它不起作用。

$("#area").focus();
$(document).click(function() { $("#area").focus() };
$("#input").click(function() { $("#input").focus() };

想法?

【问题讨论】:

    标签: jquery input focus


    【解决方案1】:

    改成

    $("#area").focus();
    $(document).click(function() { $("#area").focus() });
    $("#input").click(function(e) { e.stopPropagation(); $("#input").focus() });
    

    这将阻止事件冒泡到文档,并且只会被#input捕获

    【讨论】:

    • $(document).click(function() { $("#area").focus() }; 应该是 $(document).click(function() { $("#area ").focus() });
    【解决方案2】:

    stopPropogation 解决方案比我将要建议的更简单,但可能值得讨论这个其他选项。在你得到的第一个函数中,你可以尝试将第一个参数传递给函数,它是一个 jQuery 规范化事件对象:

    $(document).click(function(event) { ...
    

    并对其进行测试以查看事件的 target 属性是否是您的输入:

    $(document).click(function(event) {
        if(! (event.target == $("#input").get(0)) )
            $("#area").focus();
    }
    

    【讨论】:

    • +1,这样做的额外好处是您只需要一个函数来处理这两种情况。另外的缺点是,对于 IE,您需要针对 event.srcElement 进行测试,这增加了复杂性..
    • 注意event是IE中的保留关键字,当你使用它作为变量时会报错。此外,您提供的支票可以写成更简单(更短)为if ($(event.target).is('#input'))
    【解决方案3】:

    您需要在单击正常输入时取消事件冒泡,方法是在事件处理程序中返回 false 或调用 e.stopPropagation()。

    我不确定您分配事件处理程序的顺序是否重要,但您可以尝试将 #input 事件放在首位。

    【讨论】:

      猜你喜欢
      • 2020-12-27
      • 1970-01-01
      • 2012-05-14
      • 2013-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多