2014-10-20 100 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()”在输入文本字段...秀!