首页 > 技术文章 > JQ控制多个文本框获取、失去鼠标焦点事件

cnchenjunbiao 2015-05-18 16:06 原文

代码一:

  1. $(".username").focus(function(){
  2. var inputValue=$(this).val();
  3. if(inputValue=="用户名/邮箱地址"){
  4. $(this).val("");
  5. }
  6. }).blur(function(){
  7. var inputValue=$(this).val();
  8. if(inputValue==""){
  9. $(this).val("用户名/邮箱地址");
  10. }
  11. });
以上代码显然简洁,但需要知道input标签里面的value值,感觉不太合适。
所以使用代码二:
  1. $('.username').focus(function(){
  2. //inputValue为输入的值
  3. if(!this.inputValue){
  4. this.inputValue =this.value;
  5. }
  6. if(this.value ===this.inputValue){
  7. this.value ='';
  8. }
  9. }).blur(function(){
  10. if(this.value ===''||this.value ===null){
  11. this.value =this.inputValue;
  12. }
  13. });
其实HTML5新增了一个新属性:placeholder。在HTML代码中增加这一属性,对于不支持该属性的浏览器则可以运用JQ代码来实现。如下:
  1. <inputtype="text"class="username"placeholder="用户名/邮箱地址"value="用户名/邮箱地址"/>
 



来自为知笔记(Wiz)



推荐阅读