2014-10-20 41 views
0

我想創建與apple.com相同的交互式搜索欄(我知道還有很多其他帖子提出類似的問題),並且我試圖使用JS切換搜索欄。搜索彈出圖標:像Apple.com Angular JS

我的方法是使用jQuery:

// inserts a new search_bar 
    $(".glyphicon.glyphicon-search").on("click", function(){ 
     var search_bar = document.createElement("input"); 
     search_bar.setAttribute("type", "text"); 
     search_bar.setAttribute("class", "form-control search left rounded"); 
     search_bar.setAttribute("id", "search-bar"); 
     search_bar.setAttribute("placeholder", "search"); 
     search_bar.setAttribute("ng-model", "search.name"); 

     $(this).parent().replaceWith(search_bar); 

    }); 

HTML:

<span class="glyphicon glyphicon-search" style="color:white;"></span> 

此功能替換後點擊搜索(輸入標籤)欄搜索glyphicon。但是我需要一種很好的方法將搜索欄捕捉到搜索圖標上,點擊其他地方。

任何想法?

小提琴:http://jsfiddle.net/w9pwh7fr/1/


更新:

使用$( 'HTML')上( 「點擊」,函數(){})似乎爲關閉點擊事件工作。停止傳播以防止點擊圖形來觸發這兩個事件。

現在輕微的問題與搜索只能切換一次。第一次執行時。

更新小提琴: http://jsfiddle.net/w9pwh7fr/3/

+0

'$('body')。click(function(){});' – starvator 2014-10-20 18:33:55

+0

更新的小提琴,檢查出來。但問題是關閉點擊只能使用一次。如果再次重複,該元素將無法正確切換。小提琴:http://jsfiddle.net/w9pwh7fr/3/ – Ninja 2014-10-20 18:36:32

回答

0

你可以使用$('body').click(function(){});檢查在頁面上點擊。

但是,這也會檢測到搜索框上的點擊。所以,你需要檢測頁面上的點擊,除了那個框。這可以通過諸如$('body').on('click', ':not(#popup)', function(){});之類的東西來實現。

此外,this link爲您的點擊事件只爲一次工作提供答案。基本上,你刪除了綁定的處理程序,所以你需要把它們放回去。

總而言之,$('body').on('click', ':not(#popup)','.glyphicon.glyphicon-search', function(){});應該適合你!

0

完美的,只是修復它在線感謝一些建議。

更新小提琴:

http://jsfiddle.net/w9pwh7fr/4/

解決方案:

使用.hide()和.show()來切換搜索欄和搜索圖標。 使用「html」.onClick()解決單擊按鈕的問題。

$(".glyphicon.glyphicon-search").on("click", function(e){ 

    $(this).hide(); 
    $(".form-control.search").show(); 
    e.stopPropagation(); 

    }); 


    $('html').on("click", function() { 

    $(".form-control.search").hide(); 
    $(".glyphicon.glyphicon-search").show(); 

    }); 
+0

'$('html')。on(「click」...'即使在搜索框中,您的頁面上也會有任何點擊。檢查我的答案的修復。 – starvator 2014-10-20 18:52:09

0

爲什麼你當用戶點擊其他地方,你可以關閉或恢復元素只有圖標不要使用「.focusout()」在輸入文本字段...秀!