基于JQuery的PlaceHolder底文提示小插件

虽然h5有placeholder,但是ie低版本浏览器并不支持该属性,写此小插件一是为了解决兼容问题,而是为了练手,毕竟是个前端菜鸟/(ㄒoㄒ)/~~

本插件依赖于JQuery库,但并非是JQuery对象的扩展;

使用方法很简单:在js脚本中,使用提供的接口placeHolder(obj, phContent,color),参数意义依次为:元素type为text的对象、底文提示的内容、底文颜色(默认#B8B4B4)

以下为源码:

 1 /**
 2  *
 3  * @authors SimonHui (852239105@qq.com)
 4  * @Func: 兼容版的Placeholder
 5  * @date    2015-08-24 12:29:29
 6  * @version 1.0.0
 7 
 8  */
 9 
10 ;(function(window, $, undefined){
11 
12     function PlaceHoler(){};
13 
14     PlaceHoler.prototype = {
15         constructor : PlaceHoler,
16         addHandle : function(){
17             var that = this;
18             this.obj.on("keyup", function(event){
19                 var ev = event || window.event, $this = $(this);
20                 if (ev.keyCode != 8 && $this.hasClass(that.phClass)){
21                     $this.val("").removeClass(that.phClass);
22                 }else if ($this.val() == ""){
23                     $this.addClass(that.phClass).val(that.phContent);
24                 }
25             });
26 
27             this.obj.on("blur",function(){
28                 var $this = $(this);
29                 if ($this.val() == "" || $this.hasClass(that.phClass)){
30                     $this.addClass(that.phClass).val(that.phContent);
31                 }
32             });
33         },
34         init : function(obj, phContent, color){
35             this.obj = $(obj);
36             this.phContent = phContent;
37             color = color.toString().replace(/\#/g, "");
38             this.phClass = "selfPh"+color;
39 
40             this.obj.addClass(this.phClass).val(this.phContent);
41             this.addHandle();
42         }
43 
44     };
45 
46     function addClass(colorList ){
47         var phStyle = [];
48         phStyle.push('<style type="text/css">');
49         for (var i in colorList){
50             if (colorList.hasOwnProperty(i)){
51                 phStyle.push('.selfPh'+ (colorList[i]).replace(/\#/g, "")+'{color:'+ colorList[i] +' !important;}');//最高优先级样式
52             }
53         }
54         phStyle.push('</style>');
55         $("head").append(phStyle.join(""));
56     }
57 
58     var placeHolers = [], colorList=[];
59     window.placeHoler = function(obj, phContent,color){//插件入口
60         obj = obj[0] || obj;
61         if (obj.type != "text"){
62             console.log("element type must be text");
63             return;
64         }
65         placeHolers[placeHolers.length] = new PlaceHoler();
66         color = (color || "#B8B4B4");/*默认颜色#B8B4B4*/
67         placeHolers[placeHolers.length-1].init(obj, phContent, color);
68         $.inArray(color, colorList) == -1 && colorList.push(color);
69     };
70 
71     $(document).ready(function(){//添加各底文颜色样式
72         addClass(colorList);
73     });
74 })(window, jQuery);

 

posted @ 2015-08-24 21:18  SimonHui  阅读(607)  评论(0)    收藏  举报