2009-07-31 21 views
1

所以我正在爲我的網站編寫搜索字段。用戶輸入時,會在搜索建議的字段下方顯示一個框。這些建議是鍵盤可導航和可點擊的。撰寫建議搜索字段。 Javascript焦點問題

但是,當用戶單擊頁面上的其他位置時,我無法獲取建議消失。我在搜索字段中添加了一個onBlur()處理程序,但是當用戶點擊其中一個建議時,模糊發生在點擊之前,從而使建議框消失,並且點擊事件發生在死空間而不是建議。

這裏是我的HTML是什麼樣子:

<input type="text" id="search_field" onBlur="hideSuggestions()" /> 
<div id="suggestions_box"> 
    <ul> 
    <li onClick="doSomething(1)">suggestion1</li> 
    <li onClick="doSomething(2)">suggestion2</li> 
    </ul> 
</div> 

所以,問題是,我怎麼能隱藏當焦點離開搜索領域,除了的suggestions_box元素時帶有焦點的新元素是建議框?

回答

1

將您的建議框div保存在您的窗體標籤中,然後將onBlur放置在窗體上。

<form id="myform" onBlur="hideSuggestions()" > 
    <input type="text" id="search_field" /> 
    <div id="suggestions_box"> 
     <ul> 
      <li onClick="doSomething(1)">suggestion1</li> 
      <li onClick="doSomething(2)">suggestion2</li> 
     </ul> 
    </div> 
</form> 

我在想這會起作用,但現在無法測試。 w3schools上的JavaScript參考文獻說,表單標籤支持onblur,但我不知道這是否意味着它必須位於表單元素上,或者只在表單標記內。[/ edit]

0

試試這個。

首先確保你通過blur事件您hideSuggestions功能:

<input type="text" id="search_field" onblur="hideSuggestions(event)" /> 

接下來,檢查是否模糊被建議箱內的事件引起:

function hideSuggestions(event) { 
    var target = event.relatedTarget || event.toElement, 
     suggestions = document.getElementById('suggestions_box'); 

    if (contains(suggestions, target)) 
     // user did something inside suggestions box. 
     return; // Do nothing. 

    // box hiding code as before... 
} 

// contains(haystack, needle): fast lookup of whether haystack is a parent of needle. 
var contains = document.compareDocumentPosition 
      ? function(a, b) { return !!(a.compareDocumentPosition(b) & 16) } 
      : function(a, b) { return a !== b && (a.contains ? a.contains(b) : true) }; 
+1

感謝。我認爲這是一般的正確的解決方案,但我使用jquery,它沒有正確設置relatedTarget屬性(它總是未定義)。任何解決方法的想法? – Aaron 2009-08-08 04:53:22

0

我有同樣的問題,並遇到這個問題。我也使用jQuery,並且mouseout似乎是唯一一個擁有relatedTarget的事件。事實上,目前的瀏覽器可能都不支持這個功能(只需檢查Firefox 4和IE 9)。

我通過在文檔上使用mousedown解決了這個問題。我有一個變量表示正在進行搜索。如果在這種狀態下發生了mousedown,我只是檢查被點擊的目標是否具有某個類別,只用於選擇一個建議。在任何其他情況下,建議都會隱藏起來。

event.target是一個jQuery元素,你可以看看所有種類的東西,如節點名稱,ID和類名。

$(document).mousedown(function(event) { 
if (ongoingSearch) { 
    if (event.target.className != "uniqueClassname") { 
     hideSuggestions(); 
    } 
} 

});

0


在這裏,您可以使用CSS。不需要Java腳本。

該CSS將如下。

#search_field:focus+#search_box 
{ 
    display:block; 
} 
#search_box 
{ 
    display:none; 
} 
0
<input type="text" id="search_field" onBlur="hideSuggestions()" /> 
    <div id="suggestions_box"> 
     <ul> 
     <li onClick="doSomething(1)">suggestion1</li> 
     <li onClick="doSomething(2)">suggestion2</li> 
     </ul> 
    </div> 

可以使用的onclick本體元件上,然後檢查建議進行適當處理的顯示。

$('body').click(function(e){ 
    if($('.suggestions_box>ul').is(':visible')) $('.suggestions_box>ul').hide(); 
}) 

我對你參考這裏(doc truyen)的一個例子希望它會幫助你