码迷,mamicode.com
首页 > 其他好文 > 详细

IE8兼容placeholder的方案

时间:2015-12-22 19:22:12      阅读:266      评论:0      收藏:0      [点我收藏+]

标签:

用JavaScript解决Placeholder的IE8兼容问题

placeholder属性是HTML5新添加的属性,当input或者textarea设置了该属性后,该值的内容将作为灰色提示显示在文本框中,当文本框获得焦点时,提示文字消失,placeholder可作为输入框的提示文案

如图:

技术分享

placeholder是常用的属性,它使得input框内有很友好的提示效果。高版本浏览器都支持placeholder属性,但IE9以下版本的浏览器并不支持这一属性。这里用JavaScript实现添加对浏览器的兼容处理。

方案一:jquery实现

(当浏览器不支持placeholder属性时,克隆一个和界面相同的input框,将placeholder的值设置为其value值,覆盖在界面input框所在位置,并将界面上的input隐藏掉)

 调用方法: $(#selector).placeholder();(selector泛指css 的 id选择器)

(这里有一个问题,当文本框type=password时,引用此placeholder方案会使暗文密码变成明文密码)

  1 ;(function(window, document, $) {
  2 
  3     // Opera Mini v7 doesn’t support placeholder although its DOM seems to indicate so
  4     var isOperaMini = Object.prototype.toString.call(window.operamini) == ‘[object OperaMini]‘;
  5     var isInputSupported = ‘placeholder‘ in document.createElement(‘input‘) && !isOperaMini;
  6     var isTextareaSupported = ‘placeholder‘ in document.createElement(‘textarea‘) && !isOperaMini;
  7     var prototype = $.fn;
  8     var valHooks = $.valHooks;
  9     var propHooks = $.propHooks;
 10     var hooks;
 11     var placeholder;
 12 
 13     if (isInputSupported && isTextareaSupported) {
 14 
 15         placeholder = prototype.placeholder = function() {
 16             return this;
 17         };
 18 
 19         placeholder.input = placeholder.textarea = true;
 20 
 21     } else {
 22 
 23         placeholder = prototype.placeholder = function() {
 24             var $this = this;
 25             $this
 26                 .filter((isInputSupported ? ‘textarea‘ : ‘:input‘) + ‘[placeholder]‘)
 27                 .not(‘.placeholder‘)
 28                 .bind({
 29                     ‘focus.placeholder‘: clearPlaceholder,
 30                     ‘blur.placeholder‘: setPlaceholder
 31                 })
 32                 .data(‘placeholder-enabled‘, true)
 33                 .trigger(‘blur.placeholder‘);
 34             return $this;
 35         };
 36 
 37         placeholder.input = isInputSupported;
 38         placeholder.textarea = isTextareaSupported;
 39 
 40         hooks = {
 41             ‘get‘: function(element) {
 42                 var $element = $(element);
 43 
 44                 var $passwordInput = $element.data(‘placeholder-password‘);
 45                 if ($passwordInput) {
 46                     return $passwordInput[0].value;
 47                 }
 48 
 49                 return $element.data(‘placeholder-enabled‘) && $element.hasClass(‘placeholder‘) ? ‘‘ : element.value;
 50             },
 51             ‘set‘: function(element, value) {
 52                 var $element = $(element);
 53 
 54                 var $passwordInput = $element.data(‘placeholder-password‘);
 55                 if ($passwordInput) {
 56                     return $passwordInput[0].value = value;
 57                 }
 58 
 59                 if (!$element.data(‘placeholder-enabled‘)) {
 60                     return element.value = value;
 61                 }
 62                 if (value == ‘‘) {
 63                     element.value = value;
 64                     // Issue #56: Setting the placeholder causes problems if the element continues to have focus.
 65                     if (element != safeActiveElement()) {
 66                         // We can‘t use `triggerHandler` here because of dummy text/password inputs :(
 67                         setPlaceholder.call(element);
 68                     }
 69                 } else if ($element.hasClass(‘placeholder‘)) {
 70                     clearPlaceholder.call(element, true, value) || (element.value = value);
 71                 } else {
 72                     element.value = value;
 73                 }
 74                 // `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363
 75                 return $element;
 76             }
 77         };
 78 
 79         if (!isInputSupported) {
 80             valHooks.input = hooks;
 81             propHooks.value = hooks;
 82         }
 83         if (!isTextareaSupported) {
 84             valHooks.textarea = hooks;
 85             propHooks.value = hooks;
 86         }
 87 
 88         $(function() {
 89             // Look for forms
 90             $(document).delegate(‘form‘, ‘submit.placeholder‘, function() {
 91                 // Clear the placeholder values so they don‘t get submitted
 92                 var $inputs = $(‘.placeholder‘, this).each(clearPlaceholder);
 93                 setTimeout(function() {
 94                     $inputs.each(setPlaceholder);
 95                 }, 10);
 96             });
 97         });
 98 
 99         // Clear placeholder values upon page reload
100         $(window).bind(‘beforeunload.placeholder‘, function() {
101             $(‘.placeholder‘).each(function() {
102                 this.value = ‘‘;
103             });
104         });
105 
106     }
107 
108     function args(elem) {
109         // Return an object of element attributes
110         var newAttrs = {};
111         var rinlinejQuery = /^jQuery\d+$/;
112         $.each(elem.attributes, function(i, attr) {
113             if (attr.specified && !rinlinejQuery.test(attr.name)) {
114                 newAttrs[attr.name] = attr.value;
115             }
116         });
117         return newAttrs;
118     }
119 
120     function clearPlaceholder(event, value) {
121         var input = this;
122         var $input = $(input);
123         if (input.value == $input.attr(‘placeholder‘) && $input.hasClass(‘placeholder‘)) {
124             if ($input.data(‘placeholder-password‘)) {
125                 $input = $input.hide().next().show().attr(‘id‘, $input.removeAttr(‘id‘).data(‘placeholder-id‘));
126                 // If `clearPlaceholder` was called from `$.valHooks.input.set`
127                 if (event === true) {
128                     return $input[0].value = value;
129                 }
130                 $input.focus();
131             } else {
132                 input.value = ‘‘;
133                 $input.removeClass(‘placeholder‘);
134                 input == safeActiveElement() && input.select();
135             }
136         }
137     }
138 
139     function setPlaceholder() {
140         var $replacement;
141         var input = this;
142         var $input = $(input);
143         var id = this.id;
144         if (input.value == ‘‘) {
145             if (input.type == ‘password‘) {
146                 if (!$input.data(‘placeholder-textinput‘)) {
147                     try {
148                         $replacement = $input.clone().attr({ ‘type‘: ‘text‘ });
149                     } catch(e) {
150                         $replacement = $(‘<input>‘).attr($.extend(args(this), { ‘type‘: ‘text‘ }));
151                     }
152                     $replacement
153                         .removeAttr(‘name‘)
154                         .data({
155                             ‘placeholder-password‘: $input,
156                             ‘placeholder-id‘: id
157                         })
158                         .bind(‘focus.placeholder‘, clearPlaceholder);
159                     $input
160                         .data({
161                             ‘placeholder-textinput‘: $replacement,
162                             ‘placeholder-id‘: id
163                         })
164                         .before($replacement);
165                 }
166                 $input = $input.removeAttr(‘id‘).hide().prev().attr(‘id‘, id).show();
167                 // Note: `$input[0] != input` now!
168             }
169             $input.addClass(‘placeholder‘);
170             $input[0].value = $input.attr(‘placeholder‘);
171         } else {
172             $input.removeClass(‘placeholder‘);
173         }
174     }
175 
176     function safeActiveElement() {
177         // Avoid IE9 `document.activeElement` of death
178         // https://github.com/mathiasbynens/jquery-placeholder/pull/99
179         try {
180             return document.activeElement;
181         } catch (exception) {}
182     }
183 
184 }(this, document, jQuery));

方案二: js/jQuery实现

实现思路:

1、首先判断浏览器是否支持placeholder属性,如果不支持则使用模拟placeholder

2、创建一个label标签:<label>密码</label> 标签里面的内容为所要添加的提示文字,该文字应该从对应的input|textarea标签取得其placeholder属性值,再将label标签遮盖 到所对应的input|textarea上

3、代码实现如下:

  1 ; (function (win) {
  2 
  3     win.isPlaceholer = function () {
  4         var input = document.createElement("input");
  5         return "placeholder" in input;
  6     };
  7   
  8     win.placeholder = function () {
  9 
 10         if (!isPlaceholer()) {
 11             var Placeholder =function (obj) {
 12                 this.input = obj;
 13                 var te = obj.getAttribute(‘placeholder‘);
 14                 this.label = document.createElement(‘label‘);
 15                 this.label.innerHTML = te;
 16                 this.label.id = obj.id + ‘Label‘;
 17                 this.label.style.cssText = ‘position:absolute; text-indent:4px;color:#999999; font-size:14px;‘;
 18                 if (obj.value !== ‘‘) {
 19                     this.label.style.display = ‘none‘;
 20                 }
 21                 this.init();
 22             };
 23             Placeholder.prototype = {
 24 
 25                 getxy: function (obj) {
 26                     var left, top;
 27                     if (document.documentElement.getBoundingClientRect) {
 28                         var html = document.documentElement,
 29                         body = document.body,
 30                         pos = obj.getBoundingClientRect(),
 31                         st = html.scrollTop || body.scrollTop,
 32                         sl = html.scrollLeft || body.scrollLeft,
 33                         ct = html.clientTop || body.clientTop,
 34                         cl = html.clientLeft || body.clientLeft;
 35                         left = pos.left + sl - cl;
 36                         top = pos.top + st - ct;
 37                     } else {
 38                         while (obj) {
 39                             left += obj.offsetLeft;
 40                             top += obj.offsetTop;
 41                             obj = obj.offsetParent;
 42                         }
 43                     }
 44                     return {
 45                         left: left,
 46                         top: top
 47                     };
 48                 },
 49 
 50                 getwh: function (obj) {
 51                     return {
 52                         w: obj.offsetWidth,
 53                         h: obj.offsetHeight
 54                     };
 55                 },
 56 
 57                 setStyles: function (obj, styles) {
 58                     for (var p in styles) {
 59                         obj.style[p] = styles[p] + ‘px‘;
 60                     }
 61                 },
 62                 init: function () {
 63                     var label = this.label,
 64                     input = this.input,
 65                     getXY = this.getxy,
 66                     xy = this.getxy(input),
 67                     wh = this.getwh(input);
 68                     this.setStyles(label, { ‘width‘: wh.w, ‘height‘: wh.h, ‘lineHeight‘: 40, ‘left‘: xy.left + 8, ‘top‘: xy.top });
 69                     document.body.appendChild(label);
 70                     label.onclick = function () {
 71                         this.style.display = "none";
 72                         input.focus();
 73                     };
 74                     input.onfocus = function () {
 75                         label.style.display = "none";
 76                     };
 77                     input.onblur = function () {
 78                         if (this.value === "") {
 79                             label.style.display = "block";
 80                         }
 81                     };
 82                     if (window.attachEvent) {
 83                         window.attachEvent("onresize", function () {
 84                             var xy = getXY(input);
 85                             Placeholder.prototype.setStyles(label, { ‘left‘: xy.left + 8, ‘top‘: xy.top });
 86                         });
 87                     } else {
 88                         window.addEventListener("resize", function () {
 89                             var xy = getXY(input);
 90                             Placeholder.prototype.setStyles(label, { ‘left‘: xy.left + 8, ‘top‘: xy.top });
 91                         }, false);
 92                     }
 93                 }
 94             };
 95 
 96             var inpColl = $("#Box input:visible");//这里是页面上要添加placeholder支持的input
 97             //var inpColl = document.getElementsByTagName(‘input‘),          
 98             var textColl = document.getElementsByTagName(‘textarea‘);//这里是页面上要添加placeholder支持的textarea
 99             //var lableArr = $("#Box lable");
100             var toArray = function (coll) {
101                 for (var i = 0, a = [], len = coll.length; i < len; i++) {
102                     a[i] = coll[i];
103                 }
104                 return a;
105             };
106             var inpArr = toArray(inpColl),
107             textArr = toArray(textColl),
108 
109             placeholderArr = inpArr.concat(textArr);
110             for (var i = 0; i < placeholderArr.length; i++) {
111                 if (placeholderArr[i].getAttribute(‘placeholder‘) !== null) {
112 
113                     new Placeholder(placeholderArr[i]);
114                 }
115             }
116         }
117 
118     };
119 }(window));

方法执行后界面代码:(lable在页面上)

技术分享

IE8效果图如下:

技术分享

 

IE8兼容placeholder的方案

标签:

原文地址:http://www.cnblogs.com/meggie523/p/5067774.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!