jQuery更改输入搜索框的宽度

jQuery更改输入搜索框的宽度,jquery,input,width,selector,bind,Jquery,Input,Width,Selector,Bind,我想改变输入搜索框的宽度,只要光标被放置在输入框中 但是,一旦用户单击任何不是输入框的body元素,我希望宽度回到其原始长度。 然而,即使光标被放置在搜索框中,程序似乎也会将宽度更改回其原始长度。如何选择不是输入框的主体元素 <form class="search" action="/search"> {% if settings.search_option != "everything" %} <input type="hidden" name="type"

我想改变输入搜索框的宽度,只要光标被放置在输入框中

但是,一旦用户单击任何不是输入框的body元素,我希望宽度回到其原始长度。 然而,即使光标被放置在搜索框中,程序似乎也会将宽度更改回其原始长度。如何选择不是输入框的主体元素

<form class="search" action="/search">
   {% if settings.search_option != "everything" %}
     <input type="hidden" name="type" value="product" />
   {% endif %}
   <input type="text" name="q" class="search_box" 
    placeholder="{{ 'general.search.placeholder' | t }}" 
    value="{% if search and search.results.first.price %}{{ search.terms }}
   {% endif %}"/>
</form>

使用
focus
blur
事件:

var-input=$('input[name=“q”]”);
输入。开启(“聚焦模糊”,功能(evt){
$(this.css({width:evt.type==“focus”?“400px”:“auto”});
});

您可以将动画与
焦点
/
模糊
事件一起使用

$('.inp')。关于('focus',函数(){
$(此)。设置动画({
宽度:“400px”
},1000,函数(){
$(此).on('blur',函数(){
$(此)。设置动画({
宽度:“200px”
}, 1000);
});
});
});


您可以立即从StackOverflow使用的友好代码荧光笔中看出,有些地方确实错了。(是的,缺少引号。)你打开了双引号,比如
$(“body
但是你在哪里关闭了它们?刚刚更新。我复制错了。我想,你使用
焦点
事件,而不是
点击
谢谢@SeokjunHong我会试试它谢谢@roko我会试试的it@user21不客气。试试看!附言:不要用“自动”来代替“
您可以使用
“继承”
“初始”
或者你想要的任何东西……你知道了。我还有一个问题。当我在搜索框中键入内容时,下拉列表会出现。当我单击下拉列表中的项目时,搜索框的宽度已更改回原来的宽度,即使下拉列表没有隐藏。有没有办法将宽度更改回原来的宽度只有在下拉列表隐藏后才是原始的。同样,即使下拉列表没有显示,我也不希望宽度回到其原始长度。是否有一种方法可以将此函数的动画也写在一行中?我是否可以写if($('.search results')。Is(“:hidden”))在css中?代码类似于JSFIDLE:谢谢@el.oz的回答。我喜欢当输入模糊时将宽度设置为“继承”或“初始”时的动画效果,它不会更改回其原始宽度。如果您的意思是从父级继承宽度,则将父级宽度缓存为变量并使用它,请查看此FIDLE JSFIDLE.net/L84j4ykx/1
var input = $(this).find('input[name="q"]');

/* Part A: Change the width of the search input box to 600px when cursor was 
   click on the search box. When I comment out part B, 
   then the width will change to 600px. 
   If I does not comment out part B, the width does not change */

input.bind('click', function(){ 
   console.log("width changed");
   $(this ).css({'width' : '600px'});
});

/* Part B: When user click on any body element which is not the input box,
    change the width of the input box back to original length. 
    This code below does not work the way I want. When the cursor was placed 
    in the input box, it also executes this part of code,which is remain at its 
    original length */

$("body:not(.search_box)").bind('click', function(){ 
   $('input:text').css({'width' : 'inherit'}); 
});

/* Part B: I also tried code below, but does not return the result which I want */

$("body *:not(input:text)").bind('click', function(){ 
   $('input:text').css({'width' : 'inherit'}); 
});

/* hide the search result when click on input box and body*/
$('body').bind('click', function(){
   $('.search-results').hide();  
});