HTML5实践 -- 实现跨浏览器HTML5文字占位符 - placeholder

  转载请注明原创地址:http://www.cnblogs.com/softlover/archive/2012/11/20/2779878.html

  

  html5为web的form表单增强了一个功能,他就是input的占位符--placeholder。占位符的作用是,当input内容为空或者没有被聚焦的时候,input显示占位符的内容。这是个很棒的功能,但不是所有的浏览器都支持。本教程将向你介绍,如何使用 Modernizr 类库去判断浏览器是否支持该属性,然后使用jquery动态显示占位符。

  demo预览地址:http://webdesignerwall.com/demo/html5-placeholder-text/

  demo下载地址:http://webdesignerwall.com/file/html5-placeholder.zip

 

  以前使用JavaScript实现的方式

  在没有placeholder属性的日子里,我们使用javascript去模拟他的实现。在下面的例子里,我们向input添加了一个value属性。input聚焦的时候,我们判断value的值是否是‘search’,是的话就清空内容。当input失去焦点的时候,我们判断内容是否为空,为空就将value设置为‘search’。

<input type="text" value="Search" onfocus="if (this.value == 'Search') {this.value = '';}" 
  onblur
="if (this.value == '') {this.value = 'Search';}" />

 

  使用jquery生成占位符

  现在使用html5的placeholder,从语义上来说,他比value属性更能表达我们的意图。但是不是所有浏览器都支持该属性,所以我们需要借助 Modernizr and jQuery 来帮助我们。

  Modernizr用来判断浏览器是否支持placeholder属性,如果不支持,则运行jquery语句。他会把所有包含placeholder属性的html元素找出来,并把他存在变量中。在元素获得和失去焦点的时候,脚本会判断value值和placeholder值,来决定value值最终的内容。

  如果你想在自己的站点中使用这个功能,需要下载modernizr和jquery类库,并保证他们的引用地址正确。

<script src="jquery.js"></script>
<script src="modernizr.js"></script>

<script>
  $(document).ready(function(){
    if(!Modernizr.input.placeholder){
      $('[placeholder]').focus(function() {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
          input.val('');
          input.removeClass('placeholder');
        }
      }).blur(function() {
        var input = $(this);
        if (input.val() == '' || input.val() == input.attr('placeholder')) {
          input.addClass('placeholder');
          input.val(input.attr('placeholder'));
        }
      }).blur();
      $(
'[placeholder]').parents('form').submit(function() {         $(this).find('[placeholder]').each(function() {           var input = $(this);           if (input.val() == input.attr('placeholder')) {             input.val('');           }       })     });   } </script>

 

  移出webkit搜索框样式

  webkit浏览器为搜索框添加了额外的样式,我们需要使用下面的脚本去移出他。

input[type=search] {    -webkit-appearance: none;}

input[type="search"]::-webkit-search-decoration, 
input[type="search"]::-webkit-search-cancel-button {
    display: none;
}

  好了,本节课程到此为止。

 

  原文地址:http://webdesignerwall.com/tutorials/cross-browser-html5-placeholder-text

 

HTML5实践系列

posted @ 2012-11-24 11:34  下一站永远  阅读(2696)  评论(1编辑  收藏  举报