jquery实用技巧之输入框提示语句


我们在编写网页的时候不可避免的会遇到输入框,那么怎么设计输入框才能更加优雅呢?不同的人会有不同的答案,下面分享一个比较不错的设计。

效果图

细节

这个效果主要是通过JQuery来实现,我的思路如下:

输入框获取鼠标焦点之前,显示原标签的value属性值;获取了鼠标焦点之后,如果当前value有值,那就清空,否则恢复;密码框特殊照顾,待会讲。 

实现的代码如下:

$("#address").focus(function(){
    var address_text = $(this).val();
    if(address_text=="请输入邮箱地址"){
      $(this).val("");
    }
  });
$("#address").blur(function(){
    var address_value = $(this).val();
    if(address_value==""){
      $(this).val("请输入邮箱地址")
    }
  });

完整的小例子

完整的代码如下,尤其注意<input type="text" id="password">的实现!

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>文本输入框中内容的提示效果</title>
  <script type="text/javascript" src="jquery-2.2.4.min.js"></script>
</head>
<body>
<script>
$(function(){
  $("#address").focus(function(){
    var address_text = $(this).val();
    if(address_text=="请输入邮箱地址"){
      $(this).val("");
    }
  });
  $("#password").focus(function(){
    var password_text = $(this).val();
    if(password_text=="请输入密码"){
      $(this).attr("type","password");
      $(this).val("");
    }
  });
  $("#address").blur(function(){
    var address_value = $(this).val();
    if(address_value==""){
      $(this).val("请输入邮箱地址")
    }
  });
  $("#password").blur(function(){
    var password_value = $(this).val();
    if(password_value==""){
      $(this).attr("type","text");
      $(this).val("请输入密码")
    }
  });
});
</script>
<div align="center">
  <input type="text" id ="address" value="请输入邮箱地址"><br><br>
  <input type="text" id ="password" value="请输入密码"><br><br>
  <input type="button" name="登录" value="登陆">
</div>
</body>
</html>

$(function(){});其就是$(document).ready(function(){});的缩写。这个倒不是什么重点。

$(this).attr(“type”,”password”);将当前对象(也就是获取鼠标焦点的输入框)的属性值进行动态的改变。达到输入数据的时候以密码框的形式出现。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持phpstudy。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3