使用CSS3和jQuery可伸缩的搜索条

jerry CSS 2015年08月20日 收藏

搜索条在我们网站是必不可少的,尤其是在有限的页面空间里,放置一个重要的搜索条是个难题,今天我将结合实例给大家介绍一下如何使用CSS3和jQuery来实现一个可伸缩功能的搜索条。

在实例中,我们只展示一个搜索按钮,当点击搜索按钮时,输入框由右向左滑动展开,输入搜索内容后,点击搜索按钮则跳到搜索结果页,搜索输入框收起。

HTML

在需要放置搜索条的页面中放置如下html代码,搜索条#search_bar包含一个form#myform表单,表单中放置一个搜索输入框#search,一个搜索按钮.search_btn以及搜索按钮图标.search_ico。

  1. <div id="search_bar" class="search_bar">
  2. <form id="myform">
  3. <input class="input" placeholder="想搜点什么呢..." type="text" name="key" id="search">
  4. <input class="search_btn" type="submit" value="">
  5. <span class="search_ico"></span>
  6. </form>
  7. </div>

CSS

我们通过CSS来将整个搜索条布局美化,其中我们使用了CSS3代码。

  1. .search_bar{position: relative;margin-top: 10px;
  2. width: 0%;min-width: 60px;height: 60px;
  3. float: right;overflow: hidden;
  4. -webkit-transition: width 0.3s;
  5. -moz-transition: width 0.3s;
  6. transition: width 0.3s;
  7. -webkit-backface-visibility: hidden;
  8. background:#162934;
  9. }
  10. .input{
  11. position: absolute;top: 0;right: 0;
  12. border: none;outline: none;
  13. width: 98%;height: 60px; line-height:60px;z-index: 10;
  14. font-size: 20px;color: #f9f9f9;background:transparent
  15. }
  16. .search_ico,.search_btn {
  17. width: 60px;height: 60px;display: block;
  18. position: absolute;right: 0;top: 0;
  19. padding: 0;margin: 0;line-height: 60px;cursor: pointer;
  20. }
  21. .search_ico{background: #e67e22 url(icon.png) no-repeat 18px 20px;z-index:90;}
  22. .search_open{width: 100% !important; z-index:1002}
  23. #show{position:absolute; padding:20px}

上述代码中关键的是transition: width 0.3s;可以实现CSS3的动画效果,width由0变成100%,具体大家可以去看下CSS3手册相关介绍,这里不多描述,你可以直接复制和修改代码应用到你的项目中去。

jQuery

当点击搜索按钮时,搜索条.search_bar通过toggleClass()切换样式.search_open,这就实现了搜索条收缩和伸展功能。另外我们还需要判断输入情况,当输入满足条件时,提交搜索表单实现搜索功能,请看代码:

  1. $(function(){
  2. $(".search_ico").click(function(){
  3. $(".search_bar").toggleClass('search_open');
  4. var keys = $("#search").val();
  5. if(keys.length>2){
  6. $("#search").val('');
  7. $("#myform").submit();
  8. }else{
  9. return false;
  10. }
  11. });
  12. });

该效果可以运用到移动端项目中,当然你也可以添加手动滑动效果。

下载地址