码迷,mamicode.com
首页 > Web开发 > 详细

geekpark.js

时间:2015-07-16 18:16:15      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

  1 /**
  2  * This is a javascript library
  3  * Author: Dongdong
  4  * Version: 1.1.2
  5  * Date: 2014.06.19
  6  * Mail: mail@liyaodong.com
  7  */
  8 ‘use strict‘;
  9 
 10 $(function() {
 11   window.GeekPark = {
 12     // 滑动到某个DOM
 13     slideToDom: function(domid, offset, callback) {
 14       if (typeof callback === ‘function‘) {
 15         $(‘html,body‘).animate({
 16             scrollTop: parseInt($(domid).offset().top - offset) + ‘px‘
 17           }, 800)
 18           .promise().done(function() {
 19             callback();
 20           });
 21       } else {
 22         $(‘html,body‘).animate({
 23           scrollTop: parseInt($(domid).offset().top - offset) + ‘px‘
 24         }, 800);
 25       }
 26 
 27     },
 28 
 29     // 检测是否为retina屏幕
 30     isRetinaDisplay: function() {
 31       if (window.matchMedia) {
 32         var mq = window.matchMedia("only screen and (min--moz-device-pixel-ratio: 1.3), only screen and (-o-min-device-pixel-ratio: 2.6/2), only screen and (-webkit-min-device-pixel-ratio: 1.3), only screen  and (min-device-pixel-ratio: 1.3), only screen and (min-resolution: 1.3dppx)");
 33         if (mq && mq.matches || (window.devicePixelRatio > 1)) {
 34           return true;
 35         } else {
 36           return false;
 37         }
 38       }
 39     },
 40 
 41     // GeekPark 公用弹窗组件,需要引入GeekPark.css
 42     "alertTip": function(title, tip, type) {
 43       var mask = document.createElement(‘div‘),
 44         $body = $(‘body‘);
 45 
 46       var alertTip = {
 47         "open": function() {
 48           if (!$(‘#gptip‘).length) {
 49             $body.append(‘<div id="gptip"><div class="gptip-title">‘ + title + ‘<a href="javascript:;" class="fa fa-close gptip-close"></a></div><div class="gptip-content">‘ + tip + ‘</div><a href="javascript:;" class="confirm">确&nbsp;&nbsp;定</a></div>‘);
 50 
 51 
 52             $(mask).attr(‘id‘, ‘gptip-mask‘);
 53             $(mask).addClass(‘gptip-mask‘);
 54             $body.append(mask);
 55 
 56           }
 57 
 58           $(‘#gptip‘).addClass(‘on‘);
 59           $(‘#gptip-mask‘).addClass(‘on‘);
 60 
 61         },
 62         "close": function() {
 63           $(‘#gptip-mask‘).fadeOut(300);
 64           $(‘#gptip‘).fadeOut(300);
 65 
 66           setTimeout(function() {
 67             $(‘#gptip‘).remove();
 68             $(‘#gptip-mask‘).remove();
 69           }, 400);
 70 
 71         }
 72       };
 73 
 74       alertTip.open();
 75 
 76       $(‘#gptip a.confirm,#gptip a.gptip-close,#gptip-mask‘).click(function() {
 77         alertTip.close();
 78       });
 79 
 80       if (type == ‘error‘) {
 81         $(‘#gptip‘).addClass(‘error‘);
 82       }
 83     },
 84     // 分享
 85     // window.GeekPark.share.run(type, options)
 86     // options用法(imageView是可选的):
 87     // options ==> {title: ‘title‘, imageView: ‘img url‘}
 88     share: {
 89       openWindow: function(url) {
 90         window.open(url, ‘‘, ‘width=700, height=400, top=0, left=0, toolbar=no, menubar=no, scrollbars=no, location=yes, resizable=no, status=no‘);
 91       },
 92       run: function(type, options) {
 93         // Initialize
 94         var context = this,
 95           items = {
 96             weibo: ‘http://service.weibo.com/share/share.php?url=<%= url %>&appkey=3896321144&title=<%= title %>&pic=<%= imageURL %>&ralateUid=1735559201‘,
 97             twitter: ‘https://twitter.com/share?url=<%= url %>&text=<%= title %>‘
 98           };
 99         // Set default values
100         type = type || ‘wechat‘;
101         options = $.extend({
102           title: ‘GeekPark‘,
103           url: window.location.href,
104           imageURL: ‘‘
105         }, options);
106         if ($.inArray(type, Object.keys(items)) > -1) {
107           var tmplt = _.template(items[type]);
108           context.openWindow(tmplt(options));
109         }
110       }
111     },
112     loadingBtn: {
113       createNew: function($link, loadingGif) {
114         var img = ‘<img src="‘ + loadingGif + ‘" style="display: hidden" />‘;
115         $link.after(img);
116         var $img = $link.next(‘.loading-img‘);
117         return {
118           loading: function() {
119             $link.hide();
120             $img.show();
121           },
122           done: function() {
123             $img.hide();
124             $link.show();
125           }
126         };
127       }
128     },
129 
130     // 检测是否在微信中打开
131     isWechat: function() {
132       var ua = navigator.userAgent.toLowerCase();
133       return (/micromessenger/.test(ua)) ? true : false;
134     },
135 
136     // 去掉字符串两端的空格
137     stringTrim: function(s) {
138       return s.replace(/(^\s*)|(\s*$)/g, "");
139     },
140 
141     // 用于随机打乱数组排序
142     arrrayShuffle: function(arr) {
143       for (var i = arr.length - 1; i >= 0; i--) {
144         var randomIndex = Math.floor(Math.random() * (i + 1));
145         var itemAtIndex = arr[randomIndex];
146         arr[randomIndex] = arr[i];
147         arr[i] = itemAtIndex;
148       }
149       return arr;
150     },
151 
152     // 用于动态加载HTML模板
153     loadTemplate: function (templateURL, callback) {
154       $.ajax({
155         url: templateURL,
156         dataType: ‘html‘
157       })
158       .done(function(data) {
159         callback(data);
160       })
161       .fail(function() {
162         console.error(‘Load ‘ + templateURL + ‘ failure .‘);
163       });
164     },
165 
166     // 检测页面是否有JS权限
167     isPage: function(pageClass) {
168       return $(‘body‘).hasClass(pageClass) ? true : false;
169     },
170 
171     // 利用UA检测是否为移动设备
172     isMobile: function () {
173       return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? true : false;
174     },
175 
176     // 刷新页面
177     reload: function () {
178       document.location.reload(true);
179     },
180 
181     // 倒计时 {total: initnumber, dom: $(dom), callback: fun}
182     countDown: function (opt) {
183       var intervalID = window.setInterval(loopFunction, 1000);
184 
185       var  timer = (function () {
186         var total = opt.total || 5;
187         return {
188           minus: function () {
189             total -= 1;
190           },
191           getTotal: function () {
192             return total;
193           }
194         };
195       })();
196 
197       function loopFunction(total) {
198         if(timer.getTotal() > 0) {
199           timer.minus();
200         } else {
201           if(typeof opt.callback === ‘function‘)  {
202             opt.callback();
203             window.clearInterval(intervalID);
204           }
205         }
206 
207         $(opt.dom).text(timer.getTotal());
208       }
209 
210     } // countDown end
211 
212   }; // GeekPark object define end
213 
214   (function($, GeekPark) {
215 
216     //用于表单验证,传入form的选择器即可,eg: #myform .myform form
217     GeekPark.formValidator = function(opt) {
218       if($(opt.form).length === 0 || typeof opt.callback !== ‘function‘) {
219         console.error(‘formValidator.argument error‘);
220         return false;
221       }
222       var $form = $(opt.form);
223       /******「C」事件逻辑******/
224       $form.on(‘submit‘, function(event) {
225         event.preventDefault();
226         if(checkAll($form)) {
227           opt.callback();
228         } else {
229           highlight($form);
230         }
231       });
232 
233       // 监听blur事件
234       $form.find(‘input‘).each(function() {
235         // 寻找所有设置了校验规则的input
236         var rule = $(this).data(‘validate‘);
237         if(typeof rule == ‘string‘) {
238           var validResult;
239           // 如果已经自动聚焦则直接失去焦点时检测
240           if(typeof $(this).attr(‘autofocus‘) == ‘string‘) {
241             $(this).blur(function(event) {
242               validResult = validItem($(this), rule);
243               updateStatus(validResult, $(this));
244             });
245           } else {
246             $(this).focus(function() {
247               removeError($(this));
248               $(this).blur(function() {
249                 validResult = validItem($(this), rule);
250                 updateStatus(validResult, $(this));
251               });
252             });
253           }
254         }
255       });
256 
257       // 高亮所有错误
258       function highlight ($dom) {
259         $dom.find(‘input‘).each(function() {
260           var rule = $(this).data(‘validate‘);
261           if(rule) {
262             var validResult = validItem($(this), rule);
263             updateStatus(validResult, $(this));
264           }
265         });
266       }
267 
268     };
269 
270     /******「M」数据逻辑 ******/
271 
272     function validItem ($dom, rule) {
273       // 针对每个input进行规则校验
274       var ruleItem = rule.split(‘|‘),
275           str = $dom.val(),
276           count = 0,
277           pass = 0;
278 
279       // 默认给是否通过校验写上未通过
280       $dom.data(‘valid‘, 0);
281 
282       for (var i = 0; i < ruleItem.length; i++) {
283         // 每个表单可能有多个校验规则
284         var result = validRule(ruleItem[i], str);
285         count ++;
286         if(result) pass++;
287       };
288 
289       // 如果所有规则全部匹配成功则标记通过校验
290       if(count == pass) {
291         $dom.data(‘valid‘, 1);
292         return true;
293       } else {
294         return false;
295       }
296     }
297 
298     // 如果需要新加规则就在这里加
299     function validRule (rule, str) {
300       switch(rule) {
301         case ‘required‘:
302           return (str.length > 0) ? true : false;
303           break;
304         case ‘mobile‘:
305           return /^1\d{10}$/.test(str);
306           break;
307         case ‘email‘:
308           return /^[^@]+@([^@\.]+\.)+[^@\.]+$/.test(str);
309           break;
310         case ‘repeat-password‘:
311           return (str == $(‘#password‘).val() && str.length !== 0);
312           break;
313         default:
314           if(/^min\d+$/i.test(rule)) {
315             // min xxx
316             return (str.length >= rule.match(/\d+/)[0]);
317           } else if(/^max\d+$/i.test(rule)) {
318             return (str.length <= rule.match(/\d+/)[0]);
319           }
320           break;
321       }
322     }
323 
324     // 检查是否所有校验都已通过
325     function checkAll ($form) {
326       var count = 0,
327           pass = 0;
328       $form.find(‘input‘).each(function() {
329         var rule = $(this).data(‘validate‘);
330         if(rule) {
331           count ++;
332           if($(this).data(‘valid‘) == 1) {
333             pass ++;
334           }
335         }
336       });
337       return (count == pass && pass !== 0);
338     }
339     /******「M」数据逻辑 end ******/
340 
341     /******「V」视图逻辑 ******/
342     function addError ($dom) {
343       if(!$dom.hasClass(‘error‘)) {
344         $dom.addClass(‘error‘);
345       }
346 
347       if(!$dom.hasClass(‘shakeonce‘)) {
348         $dom.addClass(‘shakeonce‘);
349       }
350 
351       $dom.on("webkitAnimationEnd", function() {
352         $dom.removeClass(‘shakeonce‘);
353       });
354     }
355 
356     function removeError ($dom) {
357       $dom.removeClass(‘error‘);
358     }
359 
360     // 根据校验是否通过加上相关提示
361     function updateStatus (validResult, $dom) {
362       if(validResult) {
363         removeError($dom);
364       } else {
365         addError($dom);
366       }
367     }
368     /******「V」视图逻辑 end ******/
369 
370 
371   })(jQuery, GeekPark);
372 
373 }); // run delay end

原文链接:https://github.com/geekpark/geekpark.js/blob/master/src%2Fgeekpark.js

 

geekpark.js

标签:

原文地址:http://www.cnblogs.com/divcssjs/p/4651485.html

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