IE9 及以下版本不支持 placeholder属性

  • JQuery解决方法
(function () {
    
    
  // 浏览器不支持placeholder属性 
  if (!('placeholder' in document.createElement('input'))) {
    
    
    // 遍历每一个用到placeholder的input 和 textarea
    $('input[placeholder], textarea[placeholder]').each(function () {
    
    
      var that = $(this)
      var text = that.attr('placeholder')
      if (that.val() === '') {
    
      // 内容为空时,添加提示信息
        that.val(text).addClass('placeholder')
        that.css('color', '#9A9791')
      }
      that.focus(function () {
    
      // 获取焦点时,内容和提示文字相同,则清空
        if (that.val() === text) {
    
    
          that.val('').removeClass('placeholder')
          that.css('color', '')
        }
      })
      that.blur(function () {
    
     // 失去焦点时,内容为空,则添加提示信息
        if (that.val() === '') {
    
    
          that.val(text).addClass('placeholder')
          that.css('color', '#9A9791')
        }
      })
      .closest('form').submit(function () {
    
     // 父元素中有form时(标签存在于表单中)
        if (that.val() === text) {
    
    
          that.val('')
          that.css('color', '')
        }
      })
    })
  }
})()

猜你喜欢

转载自blog.csdn.net/weixin_49524462/article/details/115352078