jQuery制作input提示内容(兼容IE8以上)

来自:互联网
时间:2019-08-22
阅读:

我们都知道HTML5的input新属性有 placeholder="",那么这个不兼容IE低版本我们只能用脚本来写了。

首先HTML新建一个input

<input type="text" class="input" value="请输入搜索内容" />

然后我们再引入相应的js库,再使用jQuery

<script src="js/jquery-1.8.3.min.js"></script>
  <script>
    $(".input").bind({
      focus:function(){ 
        if (this.value == this.defaultValue){ 
          this.value=""; 
        } 
      }, 
      blur:function(){ 
        if (this.value == ""){ 
          this.value = this.defaultValue; 
        } 
      } 
    });
  </script>

简单吧,这样就可以了,那么这个是input的属性是text,我们要密码password也一样可以显示IE低版本,我们用的方法就是用两个input,一个text默认显示,一个password默认隐藏,当text获取焦点时password显示,text隐藏,没有输入内容失去焦点text显示,password显示,好了,废话不多说,看代码!

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>密码框提示</title>
</head>
<body>
  
  <input type="text" value="登录密码" class="show" >
  <input type="password" class="log_paw" style="display: none;">
  
  
  <script src="js/jquery-1.8.3.min.js"></script>
  <script>
    $('.show').focus(function(){
      var text_value = $(this).val();
      if (text_value == this.defaultValue) {
        $(this).hide();
        $(this).next('input.log_paw').show().focus();
      }
    });
    $('input.log_paw').blur(function() {
      var text_value = $(this).val();
      if (text_value == '') {
        $(this).prev('.show').show();
        $(this).hide();
      }
    });
  </script>
</body>
</html>
返回顶部
顶部