javascript 单击时平滑扩展输入字段宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25138735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:01:58  来源:igfitidea点击:

Expand input field width smoothly on click

javascriptjqueryhtmlcss

提问by user1355300

I want to display an input field .searchwhen clicking on .iconclass. I have managed to do that with following code. However instead of show/hide, I want to display the input field by smoothly expanding its width.

我想.search在点击.icon类时显示一个输入字段。我已经设法使用以下代码做到了这一点。但是,我想通过平滑扩展其宽度来显示输入字段,而不是显示/隐藏。

How that can be done?

那怎么办?

JSFiddle Demo:

JSFiddle 演示:

http://jsfiddle.net/9nPW9/

http://jsfiddle.net/9nPW9/

HTML:

HTML:

<div class="box">
    <input class="search" type="search" placeholder="Search" />
     <div class="icon"></div>  
</div>

CSS:

CSS:

.box{
    position: relative;
    width: 220px;
}

.search {    
    width: 200px;
    padding: 5px;
      -webkit-transition: all .5s ease;
    -moz-transition: all .5s ease;
    transition: all .5s ease;
    float: left;
}


.icon{
    width: 20px;
    height: 20px;
    background: red; 
    position: absolute; 
    right: 0;
}

JS:

JS:

$('.icon').click(function() {
    $('.search').toggle();
});

回答by SW4

Why not change your code to toggle a class, thus keeping a clear separation between functionality (JS) and style (CSS)

为什么不改变你的代码来切换一个类,从而在功能(JS)和样式(CSS)之间保持清晰的分离

Below is some sample code, you will likely want to edit for your precise needs.

下面是一些示例代码,您可能希望根据您的具体需求进行编辑。

Demo Fiddle

演示小提琴

JS

JS

$('.icon').click(function() {
    $('.search').toggleClass('expanded');
});

CSS

CSS

 .box {
    position: relative;
    width: 220px;
}
.search {
    width: 200px;
    max-width:0;
    padding: 5px;
    transition: all .5s ease;
    position:absolute;
    right:20px;
    box-sizing:border-box;
    opacity:0;
}
.search.expanded {
    max-width:200px;
    opacity:1;
}
.icon {
    width: 20px;
    height: 20px;
    background: red;
    position: absolute;
    right: 0;
}

回答by Bogdan Martinescu

You should use .slideToggle()or fadeToggle()

你应该使用.slideToggle()fadeToggle()

$('.icon').click(function() {
    $('.search').slideToggle(500);
});