2013-01-16 190 views
2

我試圖創建一個搜索欄,一旦點擊就會展開。當用戶點擊其他地方時,搜索欄將返回到正常狀態。jquery點擊關閉功能

我還沒有設法做到這一點,但已經使它擴大點擊。任何幫助將是巨大的

$(document).ready(function(){ 
    $("#search").click(function(){ 
     $(this).animate({ "width": "200px"},400); 
    }); 
}); 
+0

嘗試更多的東西... – Neal

回答

4
$("#search").on('click', function(){ 
    $(this).animate({ "width": "200px"},400); 
}); 

$(document).on('click', ':not(#search)', function(e){ 
    //when you click somewhere that is **not** search 
    if(e.target.id !== 'search') { 
     $("#search").animate({ "width": "50px"},400); 
    } 
}); 

演示:http://jsfiddle.net/maniator/2W2z4/

1
$('body').click(function(e){ 
     if(e.target.id == 'search') 
      {  
       $(e.target).animate({ "width": "200px"},400); 
      } 
     else 
      { 
      $('#search').animate({ "width": "100px"},400); 
      } 

}); 
+0

Ÿü不要使用'e.target'代替' 「#搜尋」 的'(if語句的第1部分)? – Neal

+0

因爲當你的目標外部搜索它動畫目標,但我想我可以改變第一個動畫到e.target – Anton

+1

因此,我說:「第一部分的if語句」:-P @anton – Neal

1

爲什麼將其綁定到身體,總是有它試圖動畫即使用戶不與它交互的搜索框?

$(document).ready(function() { 
    $("#search").focus(function() { 
     $(this).animate({ "width": "600px" }, 400); 
    }).focusout(function() { 
     $(this).animate({ "width": "400px" }, 400); 
    }); 
}); 

的jsfiddle:http://jsfiddle.net/2W2z4/3/

+0

呵呵,甚至使用'focus'和'blur'都可以! **'+ 1' ** – Neal