helper.js 16 KB

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