2014-10-28 60 views
1

在這個小提琴中有一個div,其中包含兩個元素。單擊兒童時如何不失去元素焦點

http://jsfiddle.net/nxujqocw/

HTML:

<div tabindex=0> 
    <input type="text" value="hello"/> 
    <input type="button" class="hidden" value ="hola"/> 
</div> 

的Javascript:

$(document).ready(function() { 
    $("div").focusin(function() { 
     console.log("focus in"); 
     $("input[type=button]").removeClass("hidden"); 
    }); 
    $("div").focusout(function() { 
     console.log("focus out"); 
     $("input[type=button]").addClass("hidden"); 
    }); 
}); 

我想以下行爲發生: 如果我點擊DIV(包括兒童)裏面,我想裏面有一個按鈕可以出現。

在鉻中,如果我讓按鈕出現,然後單擊它,會發生什麼是焦點丟失並重新獲得,這對我來說很好,即使它在技術上不正確。

但在Firefox重點不恢復。

我該如何做到這一點?

+0

只能有一個聚焦元件。 – Oriol 2014-10-28 18:42:30

+0

同意,但如何解決呢? – Erandros 2014-10-28 18:47:08

+0

「focusout」的用法是嘗試使用「blur」事件 – 2014-10-28 18:54:32

回答

1

的問題是,當文本輸入是重點,你按一下按鈕,

  1. 首先,focusout被觸發文字輸入,隱藏按鈕
  2. 然後,因爲按鈕被隱藏,它無法獲得焦點,因此focusin未被觸發。

你能解決這個問題是這樣的:

  • focusout事件偵聽器,而不是立即隱藏元素,使用setTimeout
  • focusout事件偵聽器中,如果它尚未運行,請清除超時。

var $target = $("input[type=button]"), 
 
    timer; 
 
$("div") 
 
.focusin(function() { 
 
    clearTimeout(timer); 
 
    $target.removeClass("hidden"); 
 
}) 
 
.focusout(function() { 
 
    timer = setTimeout(function() { 
 
     $target.addClass("hidden"); 
 
    }, 0); 
 
});
.hidden { 
 
    display: none; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div tabindex="0"> 
 
    <input type="text" value="hello"/> 
 
    <input type="button" class="hidden" value="hola" /> 
 
</div>