代码之家  ›  专栏  ›  技术社区  ›  Mark Bell

jQuery:如果接收焦点的元素是特定类型的,如何取消模糊事件?

  •  0
  • Mark Bell  · 技术社区  · 14 年前

    <span class="input select">   
        <span id="select-select1" class="select-input"><span><span>This is the second option <a class="button" href="#"></a></span></span></span>    
        <span id="select-select1-options" class="select-options">
            <a value="1" href="#"><span>This is the first option</span></a>
            <a value="2" href="#"><span>This is the second option</span></a>
            <a value="3" href="#"><span>This is the third option</span></a>
        </span>    
        <select name="select1" id="select1" tabindex="2">
            <option value="1">This is the first option</option>
            <option value="2">This is the second option</option>
            <option selected="selected" value="3">This is the third option</option>
        </select>
    </span>
    

    当用户对字段进行标签或单击时,他们实际上会将焦点放在隐藏的select上;然后,父跨度将被高亮显示(添加了一个CSS类),以便它们可以看到哪个字段具有焦点。

    $('.input select').bind('focus', function() {
    
        $(this).closest('.input').addClass('focused');
    
    }).bind('blur', function(e) {
    
        $(this).closest('.input').removeClass('focused');
    
    });
    

    然而,发生了以下事情:

    1. 用户单击自定义选择。将高亮显示范围以显示其具有焦点,并显示选项锚定。
    2. 用户单击一个选项,选项锚再次隐藏。但是,因为单击的选项是一个锚定,所以它会接收焦点,并且主select高亮显示会在它应该停留的时候消失(因为我们仍然希望select具有焦点)。

    因此,我试图实现的是,当自定义select控件中的一个锚点被单击时,它不会在隐藏的select输入上触发blur事件。

    最好的办法是什么?

    抱歉,如果这有点混乱,很难解释清楚!

    1 回复  |  直到 14 年前
        1
  •  1
  •   David Tang    14 年前

    实际上,我正在构建一个定制的selectbox替代品,同时我发现当前的所有解决方案都有所欠缺。你可以试试 e.preventDefault() $(this).closest('input').focus();

    $('.input').attr("tabindex", $('.input select').attr("tabindex") || "0");
    

    然后通过完全隐藏来防止隐藏的输入捕获焦点:

    $('.input select').hide();