最近在设计班级网站的首页,模仿别人博客里使用到的可伸缩的搜索框,刚开始想想觉得挺奇妙的,后来发现这其实不难,利用之前 Css 学过的 duration 就可以实现了。下面是我从班级首页中抽出来的搜索框制作成的 Demo,跟大家分享下。我们先看看 Css 代码:
.box {
position: absolute;
margin-top: 36px;
text-align: left;
}
.assistive{
position: absolute !important;
clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
clip: rect(1px, 1px, 1px, 1px);
}
#searchArea{ /* 注意要使用 id,而不能使用 class,否则样式无效 */
font-size: 14px;
font-family: Microsoft Yahei, Arial, Sans-serif;
float:left;
width: 90px;
height: 22px;
line-height: 22px;
padding: 4px 10px 4px 28px;
background: url(../images/search.jpg) no-repeat 5px 6px;
background-color: #f9f9f9;
border: 1px solid #bbb;
-webkit-border-radius:5px;
-moz-border-radius:5px;
border-radius:5px;
outline:none;
-webkit-transition-property: width, background;
-webkit-transition-duration: 400ms;
-webkit-transition-timing-function: ease;
-moz-transition-property: width, background;
-moz-transition-duration: 400ms;
-moz-transition-timing-function: ease;
transition-property: width, background;
transition-duration: 400ms;
transition-timing-function: ease;
}
#searchArea:focus {
background-color: #f9f9f9;
width: 150px;
}
#searchSubmit{
display: none;
}
下面是相应的 Html 代码:
<div class="box">
<form method="get" action="" name="searchBox" id="searchForm">
<label for="searchArea" class="assistive">搜索</label>
<input type="text" class="field" name="searchArea" id="searchArea" placeholder="搜索" />
<input type="submit" class="submit" name="searchSubmit" id="searchSubmit" value="搜索" />
</form>
</div>
Ok! 这里有必要解释下,我在编写这个搜索框中遇到的问题,一个是隐藏不见的搜索按钮,利用 display:none; 来隐藏按钮,页面 Html 实际代码仍需要编写,而且type="submit" 这个很重要,它关系到一个可传递表单的完整性,刚开始我没有注意到添加这个,导致 enter 提交后地址栏没有变化。这里的表单使用 get 方式传递参数内容,我们发现搜索内容可以在地址后面显示。这个对于搜索来说没什么问题,因为它不涉及到什么安全问题,但对于有密码的表单,比如说登录框,我们就不能选择 get 来传递了,只能使用保密性好的 post 来传递。
另外一个问题是,duration 的使用。确切的说不是 duration 的使用本身,而是 id 的使用。刚开始,我没有在 html 中使用一个 id,全部是 class,这时候问题来了,class 下的样式不能完全的在页面中显示,比如说这里的 duration ease 滑动效果。为什么会这样?仔细思考下,原来是 display:none; 在作怪,它会隔断一些类的作用,而 id 的作用权限高于 class,这里我们需要通过 id 来更有效的定义样式。
Ok! So much! 我们去看看 效果 Demo 哈!