搜索条在我们网站是必不可少的,尤其是在有限的页面空间里,放置一个重要的搜索条是个难题,今天我将结合实例给大家介绍一下如何使用CSS3和jQuery来实现一个可伸缩功能的搜索条。
HTML
在需要放置搜索条的页面中放置如下html代码,搜索条#search_bar包含一个form#myform表单,表单中放置一个搜索输入框#search,一个搜索按钮.search_btn以及搜索按钮图标.search_ico。
<divid="search_bar"class="search_bar">
<formid="myform">
<inputclass="input"placeholder="想搜点什么呢..."
type="text"name="key"id="search">
<inputclass="search_btn"type="submit"value="">
<spanclass="search_ico"></span>
</form>
</div>
CSS
我们通过CSS来将整个搜索条布局美化,其中我们使用了CSS3代码。
.search_bar{position:relative;margin-top:10px;
width:0%;min-width:60px;height:60px;
float:right;overflow:hidden;
-webkit-transition:width0.3s;
-moz-transition:width0.3s;
transition:width0.3s;
-webkit-backface-visibility:hidden;
background:#162934;
}
.input{
position:absolute;top:0;right:0;
border:none;outline:none;
width:98%;height:60px;line-height:60px;z-index:10;
font-size:20px;color:#f9f9f9;background:transparent
}
.search_ico,.search_btn{
width:60px;height:60px;display:block;
position:absolute;right:0;top:0;
padding:0;margin:0;line-height:60px;cursor:pointer;
}
.search_ico{background:#e67e22url(icon.png)no-repeat18px20px;z-index:90;}
.search_open{width:100%!important;z-index:1002}
#show{position:absolute;padding:20px}
上述代码中关键的是transition: width 0.3s可以实现CSS3的动画效果,width由0变成100%,具体大家可以去看下CSS3手册相关介绍,这里不多描述,你可以直接复制和修改代码应用到你的项目中去。
jQuery
当点击搜索按钮时,搜索条.search_bar通过toggleClass()切换样式.search_open,这就实现了搜索条收缩和伸展功能。另外我们还需要判断输入情况,当输入满足条件时,提交搜索表单实现搜索功能,请看代码:
$(function(){
$(".search_ico").click(function(){
$(".search_bar").toggleClass('search_open');
varkeys=$("#search").val();
if(keys.length>2){
$("#search").val('');
$("#myform").submit();
}else{
returnfalse;
}
});
});
该效果可以运用到移动端项目中,当然你也可以添加手动滑动效果。