全网整合营销服务商

电脑端+手机端+微信端=数据同步管理

免费咨询热线:400-708-3566

jQuery封装placeholder效果实现方法,让低版本浏览器支持该效果

页面中的输入框默认的提示文字一般使用placeholder属性就可以了,即:

<input type="text" name="username" placeholder="请输入用户名" value="" id="username"/>

最多加点样式控制下默认文字的颜色

input::-webkit-input-placeholder{color:#AAAAAA;}

但是在低版本的浏览器却不支持这个placeholder属性,那么真的要在低版本浏览器也要实现跟placeholder一样的效果,就需要写个插件来兼容下,下面就细讲一下怎样用jquery来实现这个模拟效果。

实现这个模拟效果,页面的一般调用方式:

$('input').placeholder();

首先,先写jquery插件的一般结构:

;(function($){
  $.fn.placeholder = function(){
    //实现placeholder的代码
  }
})(jQuery)

下面我们就要判断浏览器是否支持placeholder属性。

;(function($){
  $.fn.placeholder = function(){

    this.each(function(){
      var _this = this;
      var supportPlaceholder = 'placeholder' in document.createElement('input');
      if(!supportPlaceholder){
        //不支持placeholder属性的操作

      }
    });
  }
})(jQuery)

我们要支持链式操作,如下:

;(function($){
  $.fn.placeholder = function(){

     return this.each(function(){
      var _this = this;
      var supportPlaceholder = 'placeholder' in document.createElement('input');
      if(!supportPlaceholder){
        //不支持placeholder属性的操作

      }
    });
  }
})(jQuery)

默认配置项:

options = $.extend({
  placeholderColor:'#aaaaaa',
  isSpan:false, //是否使用插入span标签模拟placeholder的方式,默认是不需要
  onInput:true //实时监听输入框
},options);

如果不需要通过span来模拟placeholder效果,那么就需要通过输入框的value值来判断,如下代码:

if(!options.isSpan){
  $(_this).focus(function () {
    var pattern = new RegExp("^" + defaultValue + "$|^$");
    pattern.test($(_this).val()) && $(_this).val('').css('color', defaultColor);
  }).blur(function () {
    if($(_this).val() == defaultValue) {
      $(_this).css('color', defaultColor);
    }
    else if($(_this).val().length == 0) {
      $(_this).val(defaultValue).css('color', options.placeholderColor)
    }
  }).trigger('blur');
}

如果需要同span标签来模拟placeholder效果,代码如下:

var $simulationSpan = $('<span class="wrap-placeholder">'+defaultValue+'</span>');
$simulationSpan.css({
  'position':'absolute',
  'display':'inline-block',
  'overflow':'hidden',
  'width':$(_this).outerWidth(),
  'height':$(_this).outerHeight(),
  'color':options.placeholderColor,
  'margin-left':$(_this).css('margin-left'),
  'margin-top':$(_this).css('margin-top'),
  'padding-left':parseInt($(_this).css('padding-left')) + 2 + 'px',
  'padding-top':_this.nodeName.toLowerCase() == 'textarea' ? parseInt($(_this).css('padding-top')) + 2 : 0,
  'line-height':_this.nodeName.toLowerCase() == 'textarea' ? $(_this).css('line-weight') : $(_this).outerHeight() + 'px',
  'font-size':$(_this).css('font-size'),
  'font-family':$(_this).css('font-family'),
  'font-weight':$(_this).css('font-weight')
});

//通过before把当前$simulationSpan添加到$(_this)前面,并让$(_this)聚焦
$(_this).before($simulationSpan.click(function () {
  $(_this).trigger('focus');
}));

//当前输入框聚焦文本内容不为空时,模拟span隐藏
$(_this).val().length != 0 && $simulationSpan.hide();

if (options.onInput) {
  //绑定oninput/onpropertychange事件
  var inputChangeEvent = typeof(_this.oninput) == 'object' ? 'input' : 'propertychange';
  $(_this).bind(inputChangeEvent, function () {
    $simulationSpan[0].style.display = $(_this).val().length != 0 ? 'none' : 'inline-block';
  });
}else {
  $(_this).focus(function () {
    $simulationSpan.hide();
  }).blur(function () {
    /^$/.test($(_this).val()) && $simulationSpan.show();
  });
};

整体代码

;(function($){
  $.fn.placeholder = function(options){
    options = $.extend({
      placeholderColor:'#aaaaaa',
      isSpan:false, //是否使用插入span标签模拟placeholder的方式,默认是不需要
      onInput:true //实时监听输入框
    },options);

     return this.each(function(){
      var _this = this;
      var supportPlaceholder = 'placeholder' in document.createElement('input');
      if(!supportPlaceholder){
        //不支持placeholder属性的操作
        var defaultValue = $(_this).attr('placeholder');
        var defaultColor = $(_this).css('color');
        if(!options.isSpan){
          $(_this).focus(function () {
            var pattern = new RegExp("^" + defaultValue + "$|^$");
            pattern.test($(_this).val()) && $(_this).val('').css('color', defaultColor);
          }).blur(function () {
            if($(_this).val() == defaultValue) {
              $(_this).css('color', defaultColor);
            }
            else if($(_this).val().length == 0) {
              $(_this).val(defaultValue).css('color', options.placeholderColor)
            }
          }).trigger('blur');
        }else{
          var $simulationSpan = $('<span class="wrap-placeholder">'+defaultValue+'</span>');
          $simulationSpan.css({
            'position':'absolute',
            'display':'inline-block',
            'overflow':'hidden',
            'width':$(_this).outerWidth(),
            'height':$(_this).outerHeight(),
            'color':options.placeholderColor,
            'margin-left':$(_this).css('margin-left'),
            'margin-top':$(_this).css('margin-top'),
            'padding-left':parseInt($(_this).css('padding-left')) + 2 + 'px',
            'padding-top':_this.nodeName.toLowerCase() == 'textarea' ? parseInt($(_this).css('padding-top')) + 2 : 0,
            'line-height':_this.nodeName.toLowerCase() == 'textarea' ? $(_this).css('line-weight') : $(_this).outerHeight() + 'px',
            'font-size':$(_this).css('font-size'),
            'font-family':$(_this).css('font-family'),
            'font-weight':$(_this).css('font-weight')
          });

          //通过before把当前$simulationSpan添加到$(_this)前面,并让$(_this)聚焦
          $(_this).before($simulationSpan.click(function () {
            $(_this).trigger('focus');
          }));

          //当前输入框聚焦文本内容不为空时,模拟span隐藏
          $(_this).val().length != 0 && $simulationSpan.hide();

          if (options.onInput) {
            //绑定oninput/onpropertychange事件
            var inputChangeEvent = typeof(_this.oninput) == 'object' ? 'input' : 'propertychange';
            $(_this).bind(inputChangeEvent, function () {
              $simulationSpan[0].style.display = $(_this).val().length != 0 ? 'none' : 'inline-block';
            });
          }else {
            $(_this).focus(function () {
              $simulationSpan.hide();
            }).blur(function () {
              /^$/.test($(_this).val()) && $simulationSpan.show();
            });
          };
        }
      }
    });
  }
})(jQuery);

调用方式,需要通过span标签来模拟的话:

$("#username").placeholder({
  isSpan:true
});

以上这篇jQuery封装placeholder效果实现方法,让低版本浏览器支持该效果就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。


# jquery封装placeholder  # OpenStack Heat AutoScaling详解及实例代码  # jQuery实现IE输入框完成placeholder标签功能的方法  # 使用 tke-autoscaling-placeholder 实现秒级弹性伸缩的方法  # 输入框  # 不需要  # 不支持  # 给大家  # 链式  # 绑定  # 为空  # 并让  # 版本浏览器  # 最多  # 也要  # 要在  # 希望能  # 请输入  # 这篇  # 来实现  # 小编  # 大家多多  # 就可以  # 先写 


相关文章: 导航网站建站方案与优化指南:一站式高效搭建技巧解析  如何选择PHP开源工具快速搭建网站?  个人摄影网站制作流程,摄影爱好者都去什么网站?  视频网站制作教程,怎么样制作优酷网的小视频?  网站制作说明怎么写,简述网页设计的流程并说明原因?  网站制作知乎推荐,想做自己的网站用什么工具比较好?  湖北网站制作公司有哪些,湖北清能集团官网?  如何用狗爹虚拟主机快速搭建网站?  如何快速搭建虚拟主机网站?新手必看指南  武汉网站制作费用多少,在武汉武昌,建面100平方左右的房子,想装暖气片,费用大概是多少啊?  昆明网站制作哪家好,昆明公租房申请网上登录入口?  详解ASP.NET 生成二维码实例(采用ThoughtWorks.QRCode和QrCode.Net两种方式)  Python lxml的etree和ElementTree有什么区别  制作公司内部网站有哪些,内网如何建网站?  学校建站服务器如何选型才能满足性能需求?  电影网站制作价格表,那些提供免费电影的网站,他们是怎么盈利的?  建站之星×万网:智能建站系统+自助建站平台一键生成  网站图片在线制作软件,怎么在图片上做链接?  唐山网站制作公司有哪些,唐山找工作哪个网站最靠谱?  c# 服务器GC和工作站GC的区别和设置  网站建设制作、微信公众号,公明人民医院怎么在网上预约?  宁波免费建站如何选择可靠模板与平台?  建站三合一如何选?哪家性价比更高?  在线制作视频的网站有哪些,电脑如何制作视频短片?  如何在阿里云服务器自主搭建网站?  Python路径拼接规范_跨平台处理说明【指导】  ,石家庄四十八中学官网?  如何在云指建站中生成FTP站点?  建站之星好吗?新手能否轻松上手建站?  C++时间戳转换成日期时间的步骤和示例代码  完全自定义免费建站平台:主题模板在线生成一站式服务  小捣蛋自助建站系统:数据分析与安全设置双核驱动网站优化  如何通过虚拟主机快速完成网站搭建?  网站制作怎么样才能赚钱,用自己的电脑做服务器架设网站有什么利弊,能赚钱吗?  成都品牌网站制作公司,成都营业执照年报网上怎么办理?  小程序网站制作需要准备什么资料,如何制作小程序?  建站之星各版本价格是多少?  西安专业网站制作公司有哪些,陕西省建行官方网站?  新网站制作渠道有哪些,跪求一个无线渠道比较强的小说网站,我要发表小说?  如何在Golang中使用replace替换模块_指定本地或远程路径  移民网站制作流程,怎么看加拿大移民官网?  如何选购建站域名与空间?自助平台全解析  如何快速启动建站代理加盟业务?  建站主机是什么?如何选择适合的建站主机?  建站之星五站合一营销型网站搭建攻略,流量入口全覆盖优化指南  建站之星安装后如何配置SEO及设计样式?  网站制作公司广州有几家,广州尚艺美发学校网站是多少?  实例解析Array和String方法  香港服务器网站推广:SEO优化与外贸独立站搭建策略  百度网页制作网站有哪些,谁能告诉我百度网站是怎么联系? 

您的项目需求

*请认真填写需求信息,我们会在24小时内与您取得联系。