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

原创文章 作者:月光光 2013年12月09日 21:23helloweba.com 标签:CSS3  jQuery 

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

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

HTML

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

<div id="search_bar" class="search_bar">
	<form id="myform">
		<input class="input" placeholder="想搜点什么呢..." type="text" name="key" id="search">
		<input class="search_btn" type="submit" value="">
		<span class="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: width 0.3s;
	-moz-transition: width 0.3s;
	transition: width 0.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: #e67e22 url(icon.png) no-repeat 18px 20px;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');
		var keys = $("#search").val();
		if(keys.length>2){
			$("#search").val('');
			$("#myform").submit();
		}else{
			return false;
		}
	});
});

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

声明:本文为原创文章,helloweba.net和作者拥有版权,如需转载,请注明来源于helloweba.net并保留原文链接:https://www.helloweba.net/javascript/241.html

4条评论

  • [yeah]

  • [yeah]

  • 嗯,你的方法不错

  • 看了一下,效果还是很不错的。我采用的大体思路:

    1,在 input submit 上面 z-index 覆盖一个 span 之类的。然后 JS 监听 span 的 click,点击后 span z-index 到下面消失掉,输入框出来。
    2,点击输入框和按钮之外的地方,如果输入框没有内容,就消失恢复原状,如果有,保持不动。
    3,点击 input submit 提交搜索。

    你的方法好像有个不太完美的地方,点击提交按钮之后,搜索框会缩回去,然后再跳转提交,感觉不是很好。