helper.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. (function(global,factory){
  2. typeof define == 'function' && define('helper',[],factory.bind(window));
  3. global['$h'] = factory();
  4. })(this,function(){
  5. var $h = $h || {};
  6. $h._errorMsgOptions = {offset: '80%',anim: 2,time:1200,shadeClose:true,shade:'0.1'};
  7. $h.returnErrorMsg = function(msg,fn){
  8. $h.pushMsg(msg,fn);
  9. return false;
  10. };
  11. $h._loadIndex = null;
  12. $h.pushMsg = function(msg,fn){
  13. layer.msg(msg.toString(),$h._errorMsgOptions,fn);
  14. };
  15. $h.openImage=function(href){
  16. return layer.open({
  17. type: 1,
  18. title: false,
  19. closeBtn: 0,
  20. shadeClose: true,
  21. content: '<img src="' + href + '" style="display: block;width: 100%;" />'
  22. });
  23. };
  24. $h.pushMsgOnceStatus = false;
  25. $h.pushMsgOnce = function(msg,fn){
  26. if($h.pushMsgOnceStatus) return ;
  27. $h.pushMsgOnceStatus = true;
  28. $h.pushMsg(msg,function(){
  29. fn && fn();
  30. $h.pushMsgOnceStatus = false;
  31. });
  32. }
  33. $h.MsgStyle='<style id="_h_msg_style">#_h_msg_html_show{width: 2.3rem;height: 1.8rem;background-color: rgba(0,0,0,0.8);border-radius: 0.2rem;position: fixed;left:0; right:0; top:0; bottom:0;margin:auto;z-index: 10099;}#_h_msg_html_show .msg_title{color: #ffffff;text-align: center;padding: 0.2rem;}#_h_msg_html_show .msg_image{width: 0.8rem;height: 0.8rem;margin: 0 auto;display: inherit;margin-top: 0.2rem;}</style>';
  34. $h.getMsgHthml=function (title,icon) {
  35. var html='<div id="_h_msg_html_show">';
  36. if(icon) html+='<img class="msg_image" src="/wap/first/zsff/images/msg_image/'+icon+'.png">';
  37. if(title) html+='<p class="line1 msg_title">'+title+'</p>';
  38. html+='</div>';
  39. return html;
  40. };
  41. $h.showMsg=function(opt,successFn){
  42. var $body = $('body'),title='',icon='error',endtime=1500,fn=null;
  43. if(typeof opt=='object'){
  44. title=opt.title || '';
  45. icon=opt.icon || 'error';
  46. endtime=opt.endtime || endtime;
  47. fn=opt.success || fn;
  48. }else if(typeof opt=='string'){
  49. title=opt;
  50. fn=successFn;
  51. }
  52. if(!$body.find('#_h_msg_style').length) $body.append(this.MsgStyle);
  53. $body.append(this.getMsgHthml(title,icon));
  54. setTimeout(function () {
  55. $('#_h_msg_style').remove();
  56. $('#_h_msg_html_show').remove();
  57. fn && fn();
  58. },endtime);
  59. };
  60. $h.OpenVideo=function(opt){
  61. if(typeof opt=='string') opt={U:opt};
  62. var url=opt.U || '';
  63. if(!url) return;
  64. $h.loadFFF();
  65. $h.loadClear();
  66. layer.open({
  67. type: 2,
  68. title: false,
  69. area: [window.innerWidth+'px', '360px'],
  70. shade: 0.8,
  71. closeBtn: 0,
  72. shadeClose: true,
  73. content:url,
  74. success:function () {
  75. console.log(1);
  76. }
  77. });
  78. }
  79. /**
  80. * 底部浮动框
  81. * @param msg
  82. */
  83. $h._promptStyle='<style id="_loading_bounce_style"> #_loading_bounce._prompt_hide{animation:down-hide .25s ease-in; animation-fill-mode: forwards; } #_loading_bounce{z-index: 998;position:fixed;bottom:0;background:#fff;width:100%;height:60px;box-shadow:0 1px 15px rgba(0,0,0,0.17);animation:up-show .25s ease-in}@keyframes up-show{0%{transform:translateY(60px)}100%{transform:translateY(0px)}}@keyframes down-hide{0%{transform:translateY(0px)}100%{transform:translateY(60px)}}#_loading_bounce ._double-container{height: 100%;display: table;position: absolute;width: 30%;left: 44%;} #_loading_bounce ._double-container .double-text{display: table-cell;vertical-align: middle;font-size: 12px;}.double-bounce1,.double-bounce2{width:50px;height:50px;border-radius:50%;background-color:#67CF22;opacity:.6;position:absolute;top:50%;margin-top:-25px;left:26%;-webkit-animation:bounce 2.0s infinite ease-in-out;-moz-animation:bounce 2.0s infinite ease-in-out;-o-animation:bounce 2.0s infinite ease-in-out;animation:bounce 2.0s infinite ease-in-out}.double-bounce2{-webkit-animation-delay:-1.0s;-moz-animation-delay:-1.0s;-o-animation-delay:-1.0s;animation-delay:-1.0s}@keyframes bounce{0%,100%{transform:scale(0.0)}50%{transform:scale(1.0)}}</style>';
  84. $h._promptHtml = '<div id="_loading_bounce" class="_prompt_loading"><div class="mop-css-1 double-bounce"><div class="double-bounce1"></div><div class="double-bounce2"></div></div><div class="_double-container"><span class="double-text">请稍等片刻...</span></div></div>';
  85. $h.prompt = function(msg){
  86. var $body = $('body'),$prompt = $($h._promptHtml);
  87. if(!$body.find('#_loading_bounce_style').length)
  88. $body.append($h._promptStyle);
  89. $prompt.find('.double-text').text(msg);
  90. $body.append($prompt);
  91. };
  92. $h.promptClear = function() {
  93. var that = $('._prompt_loading');
  94. that.addClass('_prompt_hide');
  95. setTimeout(function(){
  96. that.remove();
  97. },250)
  98. };
  99. $h.load = function(){
  100. if($h._loadIndex !== null) $h.loadClear();
  101. $h._loadIndex = layer.load(2, {shade: 0.3});
  102. };
  103. $h.loadFFF = function(){
  104. if($h._loadIndex !== null) $h.loadClear();
  105. $h._loadIndex = layer.load(1, {shade: [0.1,'#fff']});
  106. };
  107. $h.loadClear = function(){
  108. setTimeout(function(){
  109. layer.close($h._loadIndex);
  110. },250);
  111. };
  112. $h.uploadFile = function (name,url,successFn,errorFn) {
  113. $.ajaxFileUpload({
  114. url: url,
  115. type: 'post',
  116. secureuri: false, //一般设置为false
  117. fileElementId: name, // 上传文件的id、name属性名
  118. dataType: 'json', //返回值类型,一般设置为json、application/json
  119. success:successFn,
  120. error: errorFn
  121. });
  122. };
  123. $h.ajaxUploadFile = function (name,url,fnGroup) {
  124. fnGroup.start && fnGroup.start();
  125. $.ajaxFileUpload({
  126. url: url,
  127. type: 'POST',
  128. secureuri: false, //一般设置为false
  129. fileElementId: name, // 上传文件的id、name属性名
  130. dataType: 'JSON', //返回值类型,一般设置为json、application/json
  131. success:function(res,status){
  132. fnGroup.success && fnGroup.success(res,status);
  133. fnGroup.end && fnGroup.end(res,status);
  134. // var fileInput = $("#"+name),html = fileInput.prop('outerHTML'),p = fileInput.parent();
  135. // fileInput.remove();
  136. // p.append(html);
  137. },
  138. error: function(res,status){
  139. fnGroup.error && fnGroup.error(res,status);
  140. fnGroup.end && fnGroup.end(res,status);
  141. }
  142. });
  143. };
  144. //除法函数,用来得到精确的除法结果
  145. //说明:javascript的除法结果会有误差,在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
  146. //调用:_h.Div(arg1,arg2)
  147. //返回值:arg1除以arg2的精确结果
  148. $h.div = function(arg1,arg2){
  149. var t1=0,t2=0,r1,r2;
  150. try{t1=arg1.toString().split(".")[1].length;}catch(e){}
  151. try{t2=arg2.toString().split(".")[1].length;}catch(e){}
  152. with(Math){
  153. r1=Number(arg1.toString().replace(".",""));
  154. r2=Number(arg2.toString().replace(".",""));
  155. return (r1/r2)*pow(10,t2-t1);
  156. }
  157. };
  158. //乘法函数,用来得到精确的乘法结果
  159. //说明:javascript的乘法结果会有误差,在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
  160. //调用:_h.Mul(arg1,arg2)
  161. //返回值:arg1乘以arg2的精确结果
  162. $h.Mul = function(arg1,arg2) {
  163. var m=0,s1=arg1.toString(),s2=arg2.toString();
  164. try{m+=s1.split(".")[1].length}catch(e){}
  165. try{m+=s2.split(".")[1].length}catch(e){}
  166. return Number(s1.replace(".","")) * Number(s2.replace(".","")) / Math.pow(10,m);
  167. };
  168. //加法函数,用来得到精确的加法结果
  169. //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
  170. //调用:_h.Add(arg1,arg2)
  171. //返回值:arg1加上arg2的精确结果
  172. $h.Add = function(arg1,arg2){
  173. var r1,r2,m;
  174. try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
  175. try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
  176. m=Math.pow(10,Math.max(r1,r2));
  177. return (arg1*m+arg2*m)/m;
  178. };
  179. //加法函数,用来得到精确的减法结果
  180. //说明:javascript的加法结果会有误差,在两个浮点数相加的时候会比较明显。这个函数返回较为精确的减法结果。
  181. //调用:_h.Sub(arg1,arg2)
  182. //返回值:arg1减去arg2的精确结果
  183. $h.Sub = function(arg1,arg2){
  184. var r1,r2,m,n;
  185. try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0}
  186. try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0}
  187. m=Math.pow(10,Math.max(r1,r2));
  188. //动态控制精度长度
  189. n=(r1>=r2)?r1:r2;
  190. return ((arg1*m-arg2*m)/m).toFixed(n);
  191. };
  192. $h.cookie = function(key,val,time) {
  193. if(val == undefined){
  194. return _helper.getCookie(key);
  195. }else if(val == null){
  196. return _helper.delCookie(key);
  197. }else{
  198. return _helper.setCookie(key,val,time);
  199. }
  200. };
  201. //操作cookie
  202. $h.setCookie = function(key,val,time){//设置cookie方法
  203. var date=new Date(); //获取当前时间
  204. if(!time) time = 1; //将date设置为n天以后的时间
  205. date.setTime(date.getTime()+time*24*3600*1000); //格式化为cookie识别的时间
  206. document.cookie=key + "=" + val +";expires="+date.toGMTString(); //设置cookie
  207. };
  208. $h.getCookie = function(key) {//获取cookie方法
  209. /*获取cookie参数*/
  210. var getCookie = document.cookie.replace(/;[ ]/g, ";"); //获取cookie,并且将获得的cookie格式化,去掉空格字符
  211. var arrCookie = getCookie.split(";"); //将获得的cookie以"分号"为标识 将cookie保存到arrCookie的数组中
  212. var tips; //声明变量tips
  213. for (var i = 0; i < arrCookie.length; i++) { //使用for循环查找cookie中的tips变量
  214. var arr = arrCookie[i].split("="); //将单条cookie用"等号"为标识,将单条cookie保存为arr数组
  215. if (key == arr[0]) { //匹配变量名称,其中arr[0]是指的cookie名称,如果该条变量为tips则执行判断语句中的赋值操作
  216. tips = arr[1]; //将cookie的值赋给变量tips
  217. break; //终止for循环遍历
  218. }
  219. }
  220. return tips;
  221. };
  222. $h.delCookie = function(key){ //删除cookie方法
  223. var date = new Date(); //获取当前时间
  224. date.setTime(date.getTime()-10000); //将date设置为过去的时间
  225. document.cookie = key + "=v; expires =" +date.toGMTString();//设置cookie
  226. };
  227. $pushCookie = function(key){
  228. var data = $h.getCookie(key);
  229. $h.delCookie(key);
  230. return data;
  231. };
  232. $h.getParmas = function getUrlParam(name) {
  233. var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
  234. var r = window.location.search.substr(1).match(reg); //匹配目标参数
  235. if (r != null) return decodeURI(r[2]); return null; //返回参数值
  236. };
  237. $h.U = function(opt){
  238. var m = opt.m || 'wap',c = opt.c || 'public_api', a = opt.a || 'index',q = opt.q || '',p = opt.p || {},_params = '',gets='',ext=opt.ext || '.html';
  239. _params = Object.keys(p).map(function(key){
  240. return key+'/'+p[key];
  241. }).join('/');
  242. if(typeof q=='object') gets = Object.keys(q).map(function (key) {
  243. return key + '=' + q[key];
  244. }).join('&');
  245. return "/"+m+"/"+c+"/"+a+(_params == '' ? '' : '/'+_params)+ext+(gets == '' ? q : '?'+gets);
  246. };
  247. $h.isLogin = function(){
  248. return !!parseInt($h.getCookie('is_login'));
  249. };
  250. $h.SplitArray=function(list,sp){
  251. if (typeof list!='object') return [];
  252. if (sp === undefined) sp=[];
  253. for (var i = 0; i < list.length;i++){
  254. sp.push(list[i]);
  255. }
  256. return sp;
  257. }
  258. $h.EventUtil ={
  259. addHandler: function (element, type, handler) {
  260. if (element.addEventListener)
  261. element.addEventListener(type, handler, false);
  262. else if (element.attachEvent)
  263. element.attachEvent("on" + type, handler);
  264. else
  265. element["on" + type] = handler;
  266. },
  267. removeHandler: function (element, type, handler) {
  268. if(element.removeEventListener)
  269. element.removeEventListener(type, handler, false);
  270. else if(element.detachEvent)
  271. element.detachEvent("on" + type, handler);
  272. else
  273. element["on" + type] = handler;
  274. },
  275. /**
  276. * 监听触摸的方向
  277. * @param target 要绑定监听的目标元素
  278. * @param isPreventDefault 是否屏蔽掉触摸滑动的默认行为(例如页面的上下滚动,缩放等)
  279. * @param upCallback 向上滑动的监听回调(若不关心,可以不传,或传false)
  280. * @param rightCallback 向右滑动的监听回调(若不关心,可以不传,或传false)
  281. * @param downCallback 向下滑动的监听回调(若不关心,可以不传,或传false)
  282. * @param leftCallback 向左滑动的监听回调(若不关心,可以不传,或传false)
  283. */
  284. listenTouchDirection: function (target, upCallback,isPreventDefault, rightCallback, downCallback, leftCallback) {
  285. this.addHandler(target, "touchstart", handleTouchEvent);
  286. this.addHandler(target, "touchend", handleTouchEvent);
  287. this.addHandler(target, "touchmove", handleTouchEvent);
  288. var startX;
  289. var startY;
  290. function handleTouchEvent(event) {
  291. switch (event.type){
  292. case "touchstart":
  293. startX = event.touches[0].pageX;
  294. startY = event.touches[0].pageY;
  295. break;
  296. case "touchend":
  297. var spanX = event.changedTouches[0].pageX - startX;
  298. var spanY = event.changedTouches[0].pageY - startY;
  299. if(Math.abs(spanX) > Math.abs(spanY)) {
  300. if (spanX > 30)
  301. rightCallback && rightCallback();
  302. else if (spanX < -30)
  303. leftCallback && leftCallback();
  304. }else {
  305. if (spanY > 30)
  306. downCallback && downCallback();
  307. else if (spanY < -30) {
  308. upCallback && upCallback();
  309. }
  310. }
  311. break;
  312. case "touchmove":
  313. // if (event.cancelable) if(!event.defaultPrevented && !isPreventDefault) event.preventDefault();
  314. break;
  315. }
  316. }
  317. }
  318. };
  319. return $h;
  320. });