解决HTML5 placeholder的方案

来源:   时间:2013-09-05 20:06:49   阅读数:11375

分享到: 0

[导读] 使低版本浏览器支持Placeholder有很多方法,都不是很完美,或多或少有点问题,且有些原生支持的浏览器在获得焦点时会清空Placeholder提示。发现知乎网的解决方法不错,特记录下windows系统中以下浏览器测试通过

使低版本浏览器支持Placeholder有很多方法,都不是很完美,或多或少有点问题,且有些原生支持的浏览器在获得焦点时会清空Placeholder提示。发现知乎网的解决方法不错,特记录下

windows系统中以下浏览器测试通过:Google Chrome 18,Firefox 12,IE 9,IE 6,Opera 11.5。在android 4.0系统也测试了下,原生浏览器及Opera Mobile12基本通过,缺陷是获得焦点时会清空Placeholder提示。

jquery.placeholder.zhihu.js部分:

 代码如下 复制代码
   /*
    * html5 placeholder pollfill
    * - 使用绝对定位内嵌层
    * - 也适用于密码域
    * 目标浏览器: IE 6~9, FF 3.5
    ```
    // 默认
    $('input[placeholder]').placeholder()
 
    // autofocus 与 placeholder 搭配时,非 webkit 清空了提示文本,推荐
    $('input[placeholder]').placeholder({
      // 将删除原有 placehodler 属性,强制用 JS 实现替代
      useNative: false,
      // focus 时不清除提示文本, keypress 有效字符时才清空
      hideOnFocus: false,
      // 附加样式
      style: {
        textShadow: 'none'
      }
    })
    ```
    */
    (function ($) {
      var attr = 'placeholder', nativeSupported = attr in document.createElement('input')
 
      $.fn.placeholder = function (options) {
        return this.each(function () {
          var $input = $(this)
 
          if ( typeof options === 'string' ) {
            options = { text: options }
          }
 
          var opt = $.extend({
            text     : '',
            style    : {},
            namespace: 'placeholder',
            useNative: true,
            hideOnFocus: true
          }, options || {})
 
          if ( !opt.text ) {
            opt.text = $input.attr(attr)
          }
 
          if (!opt.useNative) {
            $input.removeAttr(attr)
          }else if ( nativeSupported ) {
            // 仅改变文本
            $input.attr(attr, opt.text)
            return
          }
 
          var width     = $input.width(), height = $input.height()
          var box_style = ['marginTop', 'marginLeft', 'paddingTop', 'paddingLeft', 'paddingRight']
 
          var show      = function () { $layer.show() }
          var hide      = function () { $layer.hide() }
          var is_empty  = function () { return !$input.val() }
          var check     = function () { is_empty() ? show() : hide() }
 
          var position  = function () {
            var pos = $input.position()
            if (!opt.hideOnFocus) {
              // 按??藏的情况,需要移?庸?肆较袼
              pos.left += 2
            }
            $layer.css(pos)
            $.each(box_style, function (i, name) {
              $layer.css(name, $input.css(name))
            })
          }
 
          var layer_style = {
              color     : 'gray',
              cursor    : 'text',
              textAlign : 'left',
              position  : 'absolute',
              fontSize  : $input.css('fontSize'),
              fontFamily: $input.css('fontFamily'),
              display   : is_empty() ? 'block' : 'none'
          }
 
          // create
          var layer_props = {
            text  : opt.text,
            width : width,
            height: 'auto'
          }
 
          // 确保只绑定一次
          var ns = '.' + opt.namespace, $layer = $input.data('layer' + ns)
          if (!$layer) {
            $input.data('layer' + ns, $layer = $('<div>', layer_props).appendTo($input.offsetParent()) )
          }
 
          // activate
          $layer
          .css($.extend(layer_style, opt.style))
          .unbind('click' + ns)
          .bind('click' + ns, function () {
            opt.hideOnFocus && hide()
            $input.focus()
          })
 
          $input
          .unbind(ns)
          .bind('blur' + ns, check)
 
          if (opt.hideOnFocus) {
            $input.bind('focus' + ns, hide)
          }else{
            $input.bind('keypress keydown' + ns, function(e) {
              var key = e.keyCode
              if (e.charCode || (key >= 65 && key <=90)) {
                hide()
              }
            })
            .bind('keyup' + ns,check)
          }
 
          // 由于 ie 记住密码的特性,需要监听值改变
          // ie9 不支持 jq bind 此事件
          $input.get(0).onpropertychange = check
 
          position()
          check()
        })
      }
 
    })(jQuery)

html部分:

 代码如下 复制代码

<!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <!--[if lt IE 9]>
    <script src="js/html5shiv.js"></script>
    <![endif]-->
    <title>HTML5 placeholder jQuery Plugin</title>
    <style>
         body, input, textarea { font: 1em/1.4 Helvetica, Arial; }
         label code { cursor: pointer; float: left; width: 150px; }
         input { width: 14em; }
         textarea { height: 5em; width: 20em; }
         .placeholder { color: #aaa; }
         .note { border: 1px solid orange; padding: 1em; background: #ffffe0; }   
    </style>
    </head>
    <body>
         <h1>HTML5 Placeholder jQuery Plugin</h1>    
         <form id="test">
        
<p><label><code>type=search</code> <input
type="search" name="search" placeholder="Search this site…"
autofocus></label></p>
        
<p><label><code>type=text</code> <input
type="text" name="name" placeholder="e.g. John
Doe"></label></p>
        
<p><label><code>type=email</code> <input
type="email" name="email" placeholder="e.g.
address@example.ext"></label></p>
        
<p><label><code>type=url</code> <input
type="url" name="url" placeholder="e.g.
http://mathiasbynens.be/"></label></p>
        
<p><label><code>type=tel</code> <input
type="tel" name="tel" placeholder="e.g. +32 472 77 69
88"></label></p>
         <p><label for="p"><code>type=password</code> </label><input type="password" name="password" placeholder="e.g. hunter2" id="p"></p>
        
<p><label><code>textarea</code> <textarea
name="message" placeholder="Your message goes
here"></textarea></label></p>
         <p><input type="submit" value="type=submit"></p>
         </form>
         <script src="js/jquery-1.7.2.min.js"></script>    
         <script src="js/jquery.placeholder.zhihu.js"></script>
         <script>
              $(function(){              
                   var support = (function(input) {
                        return function(attr) { return attr in input }
                   })(document.createElement('input'))         
                   if ( !(support('placeholder') && $.browser.webkit) ) {              
                        $('input[placeholder],textarea[placeholder]').placeholder({
                             useNative: false, 
                             hideOnFocus: false, 
                             style: { 
                                  textShadow: 'none' 
                             } 
                        });
                   }
 
                   if ( !support('autofocus') ) {
                        $('input[autofocus]').focus()
                   }
              });
         </script>
    </body>
    </html>

html5 placeholder ie 不兼容问题 解决方案的更多相关文章

  1. 【转】HTML5移动端最新兼容问题解决方案

    1.安卓浏览器看背景图片,有些设备会模糊. 用同等比例的图片在PC机上很清楚,但是手机上很模糊,原因是什么呢? 经过研究,是devicePixelRatio作怪,因为手机分辨率太小,如果按照分辨率来显 ...

  2. HTML5移动端最新兼容问题解决方案

    1.安卓浏览器看背景图片,有些设备会模糊.用同等比例的图片在PC机上很清楚,但是手机上很模糊,原因是什么呢?经过研究,是devicePixelRatio作怪,因为手机分辨率太小,如果按照分辨率来显示网 ...

  3. IE8 不支持html5 placeholder的解决方案

    IE8不支持html5 placeholder的解决方法. /** * jQuery EnPlaceholder plug * version 1.0 2014.07.01戈志刚 * by Frans ...

  4. (转)html5 Placeholder属性兼容IE6、7方法

    使低版本浏览器支持Placeholder有很多方法,都不是很完美,或多或少有点问题,且有些原生支持的浏览器在获得焦点时会清空Placeholder提示.发现zhihu的解决方法不错,特记录下 wind ...

  5. HTML中的IE条件注释,让低版本IE也能正常运行HTML5+CSS3网站的3种解决方案

    最近的项目中,因为需要兼容IE7,IE8,IE9,解研究了IE的条件注释,顺手写下来备忘.  HTML中的IE条件注释 IE条件注释是一种特殊的HTML注释,这种注释只有IE5.0及以上版本才能理解. ...

  6. Cross-Browser HTML5 Placeholder Text

    One of the nice enhancement in HTML5 web form is being able to add placeholder text to input fields. ...

  7. HTML5 placeholder(空白提示) 属性

    原文地址:HTML5′s placeholder Attribute 演示地址: placeholder演示 原文日期: 2010年08月09日 翻译日期: 2013年8月6日 浏览器引入了许多的HT ...

  8. jquery remove()不兼容问题解决方案

      jquery remove()不兼容问题解决方案 CreationTime--2018年7月27日10点19分 Author:Marydon 1.情景展示 点击关闭,将这个div移除掉 源码展示 ...

  9. javascript window.showModalDialog不兼容goole解决方案

    window.showModalDialog不兼容goole解决方案 一.弹框方案: 1.window.open; 2.window.showModalDialog; 3.div制作窗口:(本节忽略) ...

随机推荐

  1. jQuery获取多种input值的方法

    1 if($("input[name=item][value='val']").attr('checked')==true) //判断是否已经打勾 name即控件name属性,va ...

  2. JS转换HTML转义符

    JS转换HTML转义符 //去掉html标签 function removeHtmlTab(tab) { return tab.replace(/<[^<>]+?>/g,'') ...

  3. 第一章 数据库概述、MySQL的安装和配置

      第一章 数据库概述.MySQL的安装和配置   1.为什么要使用数据库 最早是纸质文件来存储数据 缺点:不易保存,占用空间大 计算机出现以后,采用软件来进行保存(excel) 缺点:容易损坏 文件 ...

  4. why happen "WaitHandles must be less than or equal to 64"

    一.背景: 在一个项目中碰到大数据插入的问题,一次性插入20万条数据(SQL Server),并用200个线程去执行,计算需要花费多少时间,因此需要等200个线程处理完成后,记录花费的时间,需要考虑的 ...

  5. VR定制 AR定制 就找北京动软VR开发团队(VR案例 AR案例)

    我们长期承接丰交互软件.游戏项目外包: VR/AR内容应用定制.VR.AR游戏项目外包(有主流测试硬件设备) VR全景应用.视频外包 请提供贵公司的信息,我们将提供高大上的VR案例欢迎联系我们给您提供 ...

  6. 协程、异步IO

    协程,又称微线程,纤程.英文名Coroutine,协程是一种用户态的轻量级线程. 协程拥有自己的寄存器上下文和栈.协程调度切换时,将寄存器上下文和栈保存到其他地方,在切回来的时候,恢复先前保存的寄存器 ...

  7. python学习笔记——2

    Python的字符串 在最新的Python 3版本中,字符串是以Unicode编码的,也就是说,Python的字符串支持多语言. 对于单个字符的编码,Python提供了ord()函数获取字符的整数表示 ...

  8. SOAOffice和iWebOffice、NTKO的比较及其优势(转)

    http://www.cnblogs.com/liping13599168/articles/1681465.html SOAOffice和iWebOffice.NTKO的比较及其优势 近年来,市场上 ...

  9. Visual Studio 在调试时启用编辑功能

    Visual Studio边调试边修改 如果你在调试一个web应用程序的时候,想进行编辑,可以有如下两种方法:    方法一:在web项目的属性页里的web标签页,选中"启用编辑并继续&qu ...

  10. SQL优化注意事项

    sql语句优化 性能不理想的系统中除了一部分是因为应用程序的负载确实超过了服务器的实际处理能力外,更多的是因为系统存在大量的SQL语句需要优化. 为了获得稳定的执行性能,SQL语句越简单越好.对复杂的 ...