Html5/Css3 向下兼容placeholder

Css3下input标签的placeholder属性在IE10以下是不兼容的,页面加入这段JS脚本后,能够兼容IE6+

 

 1 //@charset "utf-8";
 2 /**
 3  * jquery版本要求:1.3 ~ 1.8,HTML声明请遵循W3C标准
 4  * 用来处理placeholder的插件
 5  * 兼容IE6浏览器
 6  * @author liuzhao141596@163.com
 7  * @version 1.0
 8  * @date 2014-2-24
 9  */
10 $(function($) {
11     //判断浏览器是否支持 placeholder属性
12     function isPlaceholder() {
13         var input = document.createElement('input');
14         return 'placeholder' in input;
15     }
16 
17     function changeToOriginalColor(self) {
18         var index = $(self).index();
19         var color = originalColor[$(self).index()];
20         $(self).css('color', color);
21     }
22 
23     if(!isPlaceholder()) {
24         var texts = $(':text');
25         var len = texts.length;
26         var originalColor = [];
27         for(var i = 0; i < len; i++) {
28             var self = texts[i];
29             var placeholder = $(self).attr('placeholder');
30             if($(self).val() == "" && placeholder != null) {
31                 $(self).val(placeholder);
32                 originalColor[i] = $(self).css('color');
33                 $(self).css('color', '#666');
34             }
35         }
36         texts.focus(function() {
37             if($(this).attr('placeholder') != null && $(this).val() == $(this).attr('placeholder')) {
38                 $(this).val('');
39                 changeToOriginalColor(this);
40             }
41         }).blur(function() {
42             if($(this).attr('placeholder') != null && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
43                 $(this).val($(this).attr('placeholder'));
44                 $(this).css('color', '#666');
45             }
46         });
47     }
48 });

 

效果是这样的初始状态  

文本框有文字输入

使用方法:

页面引用这段脚本就可以向下兼容placeholder  的属性,不过注意的是密码框的情况不适合!!

 

posted @ 2014-02-26 13:47  Flying_Boy  阅读(427)  评论(0编辑  收藏  举报