输入框提示在很多提示都要用到,比如搜索提示用户输入关键字,比如登录提示用户输入用户名和密码等等。比较常见的提示方式是通过onFocus和onBlur事件来监听Input的值来给出相应的提示,例:
- <input onfocus="if(this.value=='设计蜂巢')this.value = ''" onblur="if(this.value=='') this.value = '设计蜂巢'" type="text" />
我们再来看看twitter是怎么会理这个问题的!
首先来看三张图:
(1)点击前
(2)点击后
(3)键盘按下后
从上面的三张图片可以看出 当input获得焦点后提示文字成半透明状态,只要当输入文字以后提示语才渐渐消失。这种输入提示特效是不是很酷!下面来看看这个特效是怎么实现的!
看twitter的源代码
点击前和点击后:
- <div class="holding name">
- <input type="text" name="user[name]" value="" maxlength="20" />
- <span class="holder">Full name</span>
- </div>
输入文字后:
- <div class="holding name hasome">
- <input type="text" name="user[name]" value="" maxlength="20" />
- <span class="holder">Full name</span>
- </div>
看完上面的代码是不是已经明白实现的原理了呢? 没错就是通过javascript和CSS来实现的, 首先用CSS将span.holder定位到input上面来,当鼠标点击(focus)input的时候span.holder的透明度()设为0.5 当输入文字(keydown)的时候span.holder透明度()设为0,input失焦(blur)的时候判断input的值是否为空。
- .holding{position:relative; z-index:0;}
- .holding .holder {
- line-height: 28px;
- position: absolute;
- top: 0;
- z-index: 1;
- left: 8px;
- white-space: nowrap;
- cursor: text;
- color: #999;
- -webkit-transition: opacity .1s,font-size .1s;
- -moz-transition: opacity .1s,font-size .1s;
- -o-transition: opacity .1s,font-size .1s;
- z-index:1;
- }
- .hasome input {
- color:#333;
- }
- .hasome .holder {
- opacity:0;
- filter:alpha(opacity=0);
- font-size:0!important;
- }
- $(document).ready(function() {
- $(".holding input").keydown(function() {
- $(this).parent().addClass("hasome")
- }),
- $(".holding input").blur(function() {
- $.trim(a(this).val()) == "" && $(this).parent().removeClass("hasome")
- }),
- $(".holding .holder").click(function() {
- $(this).prev().focus()
- })
- })