comm.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. //ajax对象构造函数
  2. /**
  3. * [Ajax description]
  4. * @param {[type]} options [请求方式(字符串)]
  5. * @param {[dataType]} options [返回数据的格式(字符串)]
  6. * @param {[data]} options [参数(对象)]
  7. * @param {[url]} options [请求地址(字符串)]
  8. * @param {[success]} options [成功回调(函数)]
  9. * @param {[error]} options [错误回调(函数)]
  10. * @param {[async]} options [是否同步(布尔)]
  11. * 例子:
  12. * ajax({
  13. url:
  14. data:
  15. type:
  16. dataType:
  17. success:
  18. error:
  19. async:
  20. });
  21. */
  22. function ajax(options){
  23. var _this = this;
  24. //异步请求对象的完成状态
  25. this.done = 0;
  26. this.format = function(){
  27. var now = new String(new Date().getTime());
  28. return now.substr(0,now.length-5);
  29. }
  30. //格式化参数
  31. this.formatParams = function(data) {
  32. //获取地址参数
  33. var arr = [];
  34. for (var name in data) {
  35. arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
  36. }
  37. arr.push("t="+_this.format());//按分钟刷一次
  38. return arr.join("&");
  39. }
  40. //传入设置
  41. options = options || {};
  42. //请求方式
  43. options.type = (options.type || "GET").toUpperCase();
  44. options.dataType = options.dataType || "json";
  45. options.async = options.async || true;
  46. var params = _this.formatParams(options.data);
  47. //创建异步请求对象 - 第一步
  48. var xhr;
  49. //w3c标准
  50. if (window.XMLHttpRequest) {
  51. xhr = new XMLHttpRequest();
  52. }
  53. //兼容IE6及以下
  54. else if (window.ActiveObject) {
  55. xhr = new ActiveXObject('Microsoft.XMLHTTP');
  56. }
  57. //连接 和 发送 - 第二步
  58. //判断是那种类型的请求
  59. //若是get请求
  60. if (options.type == "GET") {
  61. //参数拼接
  62. if(options.url.indexOf("?")==-1) sp="?" ; else sp="&";
  63. //发送请求
  64. xhr.open("GET", options.url + sp + params,options.async);
  65. xhr.send(null);
  66. }
  67. //若是post请求
  68. else if (options.type == "POST") {
  69. //发送请求
  70. xhr.open("POST", options.url,options.async);
  71. //设置表单提交时的内容类型
  72. xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  73. //参数配置
  74. xhr.send(params);
  75. }
  76. //接收 - 第三步
  77. xhr.onreadystatechange = function() {
  78. if (xhr.readyState == 4) {
  79. //状态码
  80. var status = xhr.status;
  81. //状态码表示成功时,执行成功回调函数
  82. if (status >= 200 && status < 300 || status == 304) {
  83. //返回数据的格式
  84. //json字符串
  85. if (options.dataType == "json") {
  86. try{
  87. options.success && options.success(eval("("+xhr.responseText+")"));
  88. }
  89. catch(err){
  90. options.success && options.success(JSON.parse(xhr.responseText), xhr.responseXML);
  91. }
  92. }
  93. //普通字符串
  94. else {
  95. options.success && options.success(xhr.responseText, xhr.responseXML);
  96. }
  97. // 改变状态为完成
  98. _this.done = 1;
  99. }
  100. //如果状态码表示失败时调用错误处理回调函数
  101. else {
  102. options.error && options.error(status);
  103. // 改变状态为完成
  104. _this.done = 1;
  105. }
  106. }
  107. }
  108. }
  109. function setCookie(name,value,t){
  110. //document.cookie.setPath("/");
  111. var hour = t?t:8;
  112. var exp = new Date();
  113. exp.setTime(exp.getTime() + hour*60*60*1000);
  114. document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString()+";path=/";
  115. }
  116. function getCookie(name){
  117. //document.cookie.setPath("/");
  118. var arr, reg = new RegExp("(^| )"+name+"=([^;]*)(;|$)");
  119. if(arr=document.cookie.match(reg)){
  120. return unescape(arr[2]);
  121. }
  122. else{
  123. return null;
  124. }
  125. }
  126. /**
  127. * 获取url字段参数化
  128. * @param name 字段名
  129. */
  130. function getStr(name){
  131. var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  132. var r = window.location.search.substr(1).match(reg);
  133. if (r != null) return unescape(r[2]); return null;
  134. }
  135. //类名增加兼容
  136. function addClass(obj, cls){
  137. if (!hasClass(obj, cls)) obj.className += " " + cls
  138. }
  139. // 去除类名
  140. function removeClass(obj, cls){
  141. if (hasClass(obj, cls)) {
  142. var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
  143. obj.className = obj.className.replace(reg, ' ')
  144. }
  145. }
  146. // 查看类名
  147. function hasClass(obj, cls){
  148. // console.log(obj,cls)
  149. return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
  150. }
  151. // 缓冲运动
  152. function animate(ele,opt,callback){
  153. //设置一个变量用于判断动画数量
  154. var timerLen = 0;
  155. for(var attr in opt){
  156. creatTimer(attr);
  157. //每加一个定时器,动画数加一
  158. timerLen++;
  159. }
  160. function creatTimer(attr){
  161. var timerName = attr + 'timer';console.log(timerName)
  162. var target = opt[attr];
  163. clearInterval(ele[timerName]);
  164. ele[timerName] = setInterval(function(){
  165. // 先获取当前值
  166. var current = getComputedStyle(ele)[attr];
  167. // 提取数值:单位
  168. // 根据当前值提取单位(单位在current最后面)
  169. var unit = current.match(/[a-z]+$/);
  170. if(unit){
  171. current = current.substring(0,unit.index)*1;
  172. unit = unit[0]
  173. }else{
  174. unit = '';
  175. current *= 1;
  176. }
  177. // 计算速度
  178. var speed = (target - current)/10;
  179. // 处理speed值,防止speed为小数而造成定时器无法完成的情况
  180. // 0.3=>1,-0.3=>-1
  181. speed = speed>0 ? Math.ceil(speed) : Math.floor(speed);
  182. //对于没有单位的属性单独处理
  183. if(attr == 'opacity'){
  184. speed = speed>0?0.05:-0.05;
  185. }
  186. if(current === target){console.log("清除定时器")
  187. clearInterval(ele[timerName]);
  188. current = target - speed;
  189. //每完成一个动画,timerLen减一
  190. timerLen--
  191. //最后若timerLen数量为零,则所有动画已经执行完再执行回调函数
  192. if(typeof callback ==='function'&&timerLen==0){
  193. callback();
  194. }
  195. }
  196. ele.style[attr] = current + speed + unit;
  197. },30)
  198. };
  199. }
  200. //弹窗工具
  201. function tips(text, time) {//提示工具
  202. time = time ? time : 2000;
  203. var para = document.createElement("p");
  204. para.innerHTML = text;
  205. para.setAttribute("class", "w_tips");
  206. para.setAttribute("style", "display: block;border-radius: 10px;background-color: rgba(1,1,1,0.5);color: #FFF;padding: 14px 26px;font-size: 16px; position: fixed;left: 50%;top: 80%;z-index: 999;");
  207. document.body.appendChild(para);
  208. para.style.marginLeft = -para.offsetWidth / 2+"px";
  209. setTimeout(function() {
  210. document.body.removeChild(para);
  211. }, time);
  212. }
  213. function G(id) {
  214. return document.getElementById(id);
  215. }
  216. function S(id) {
  217. var temp = G(id);
  218. if (temp) temp.style.visibility = 'visible';
  219. }
  220. function H(id) {
  221. var temp = G(id);
  222. if (temp) temp.style.visibility = 'hidden';
  223. }
  224. var curCSS;
  225. if (window.getComputedStyle) {
  226. curCSS = function(elem, name) {
  227. name = comm.toHump(name, '-');
  228. var ret, computed = window.getComputedStyle(elem, null),
  229. style = elem.style;
  230. if (computed) ret = computed[name];
  231. if (!ret) ret = style[name];
  232. return ret;
  233. };
  234. } else if (document.documentElement.currentStyle) {
  235. curCSS = function(elem, name) {
  236. name = comm.toHump(name, '-');
  237. var ret = elem.currentStyle && elem.currentStyle[name],
  238. style = elem.style;
  239. if (!ret && style && style[name]) {
  240. ret = style[name];
  241. }
  242. return ret === '' ? 'auto': ret;
  243. };
  244. } else {
  245. curCSS = function(elem, name) {
  246. name = comm.toHump(name, '-');
  247. var style = elem.style;
  248. return style[name];
  249. };
  250. }
  251. function css(obj, name, value) {
  252. if (value === undefined) {
  253. var temp = curCSS(obj, name);
  254. if (temp === '' || temp === 'auto') temp = 0;
  255. return temp;
  256. } else {
  257. var pxs = ['left', 'top', 'right', 'bottom', 'width', 'height', 'line-height', 'font-size'];
  258. var isPx = pxs.indexOf(name) >= 0;
  259. if (isPx && !/.*px$/g.test(value + '') && value !== 'auto') value += 'px';
  260. obj.style[comm.toHump(name)] = value;
  261. }
  262. };
  263. fx = {
  264. interval: 13,
  265. tagIdx: 0,
  266. animates: {},
  267. start: function(obj, params, speed, easing, callback, tag) {
  268. var speeds = {
  269. fast: 200,
  270. normal: 400,
  271. slow: 600
  272. };
  273. speed = (typeof speed === 'string' ? speeds[speed] : speed) || speeds.normal;
  274. if (typeof easing === 'function') {
  275. tag = callback;
  276. callback = easing;
  277. easing = '';
  278. }
  279. easing = easing || 'swing';
  280. tag = tag || 'default';
  281. for (var i in this.animates) {
  282. if (i.indexOf(tag) >= 0) this.stop(i);
  283. }
  284. var oldParams = params;
  285. params = {};
  286. var canContinue = false;
  287. for (var i in oldParams) {
  288. var p = oldParams[i];
  289. if (!comm.isArray(p)) p = [css(obj, i), p];
  290. else css(obj, i, p[0]);
  291. params[i] = {
  292. start: parseFloat(p[0]),
  293. end: parseFloat(p[1])
  294. };
  295. if (params[i].start !== params[i].end) canContinue = true;
  296. }
  297. if (!canContinue) return;
  298. tag += '_' + (++this.tagIdx);
  299. this.animates[tag] = {
  300. obj: obj,
  301. params: params,
  302. speed: speed,
  303. easing: easing,
  304. callback: callback,
  305. startTime: Date.now(),
  306. idx: 0,
  307. timer: undefined
  308. };
  309. this.animates[tag].timer = setInterval(function() {
  310. var animate = fx.animates[tag];
  311. animate.idx++;
  312. var n = Date.now() - animate.startTime;
  313. if (n > animate.speed) {
  314. fx.stop(tag);
  315. return;
  316. }
  317. var percent = n / animate.speed;
  318. var pos = fx.easing[animate.easing](percent, n, 0, 1, animate.speed);
  319. for (var i in animate.params) {
  320. var p = animate.params[i];
  321. css(animate.obj, i, p.start + (p.end - p.start) * pos);
  322. }
  323. },
  324. this.interval);
  325. },
  326. stop: function(tag) {
  327. var animate = fx.animates[tag];
  328. if (!animate) return false;
  329. clearInterval(animate.timer);
  330. var ps = animate.params;
  331. for (var i in ps) css(animate.obj, i, ps[i].end);
  332. animate.callback && animate.callback();
  333. delete fx.animates[tag];
  334. return true;
  335. },
  336. easing: {
  337. linear: function(p, n, firstNum, diff) {
  338. return firstNum + diff * p;
  339. },
  340. swing: function(p, n, firstNum, diff) {
  341. return 0.5 - Math.cos(p * Math.PI) / 2;
  342. }
  343. }
  344. };
  345. function animate(obj, params, speed, easing, callback, tag) {
  346. fx.start(obj, params, speed, easing, callback, tag);
  347. };