2013-01-16 66 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