layui.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. /*!
  2. @Title: Layui
  3. @Description:经典模块化前端框架
  4. @Site: www.layui.com
  5. @Author: 贤心
  6. @License:MIT
  7. */
  8. ;!function(win){
  9. "use strict";
  10. var doc = document, config = {
  11. modules: {} //记录模块物理路径
  12. ,status: {} //记录模块加载状态
  13. ,timeout: 10 //符合规范的模块请求最长等待秒数
  14. ,event: {} //记录模块自定义事件
  15. }
  16. ,Layui = function(){
  17. this.v = '2.1.5'; //版本号
  18. }
  19. //获取layui所在目录
  20. ,getPath = function(){
  21. var js = doc.scripts
  22. ,jsPath = js[js.length - 1].src;
  23. return jsPath.substring(0, jsPath.lastIndexOf('/') + 1);
  24. }()
  25. //异常提示
  26. ,error = function(msg){
  27. win.console && console.error && console.error('Layui hint: ' + msg);
  28. }
  29. ,isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]'
  30. //内置模块
  31. ,modules = {
  32. layer: 'modules/layer' //弹层
  33. ,laydate: 'modules/laydate' //日期
  34. ,laypage: 'modules/laypage' //分页
  35. ,laytpl: 'modules/laytpl' //模板引擎
  36. ,layim: 'modules/layim' //web通讯
  37. ,layedit: 'modules/layedit' //富文本编辑器
  38. ,form: 'modules/form' //表单集
  39. ,upload: 'modules/upload' //上传
  40. ,tree: 'modules/tree' //树结构
  41. ,table: 'modules/table' //表格
  42. ,element: 'modules/element' //常用元素操作
  43. ,util: 'modules/util' //工具块
  44. ,flow: 'modules/flow' //流加载
  45. ,carousel: 'modules/carousel' //轮播
  46. ,code: 'modules/code' //代码修饰器
  47. ,jquery: 'modules/jquery' //DOM库(第三方)
  48. ,mobile: 'modules/mobile' //移动大模块 | 若当前为开发目录,则为移动模块入口,否则为移动模块集合
  49. ,'layui.all': '../layui.all' //PC模块合并版
  50. };
  51. //记录基础数据
  52. Layui.prototype.cache = config;
  53. //定义模块
  54. Layui.prototype.define = function(deps, callback){
  55. var that = this
  56. ,type = typeof deps === 'function'
  57. ,mods = function(){
  58. typeof callback === 'function' && callback(function(app, exports){
  59. layui[app] = exports;
  60. config.status[app] = true;
  61. });
  62. return this;
  63. };
  64. type && (
  65. callback = deps,
  66. deps = []
  67. );
  68. if(layui['layui.all'] || (!layui['layui.all'] && layui['layui.mobile'])){
  69. return mods.call(that);
  70. }
  71. that.use(deps, mods);
  72. return that;
  73. };
  74. //使用特定模块
  75. Layui.prototype.use = function(apps, callback, exports){
  76. var that = this
  77. ,dir = config.dir = config.dir ? config.dir : getPath
  78. ,head = doc.getElementsByTagName('head')[0];
  79. apps = typeof apps === 'string' ? [apps] : apps;
  80. //如果页面已经存在jQuery1.7+库且所定义的模块依赖jQuery,则不加载内部jquery模块
  81. if(window.jQuery && jQuery.fn.on){
  82. that.each(apps, function(index, item){
  83. if(item === 'jquery'){
  84. apps.splice(index, 1);
  85. }
  86. });
  87. layui.jquery = layui.$ = jQuery;
  88. }
  89. var item = apps[0]
  90. ,timeout = 0;
  91. exports = exports || [];
  92. //静态资源host
  93. config.host = config.host || (dir.match(/\/\/([\s\S]+?)\//)||['//'+ location.host +'/'])[0];
  94. //加载完毕
  95. function onScriptLoad(e, url){
  96. var readyRegExp = navigator.platform === 'PLaySTATION 3' ? /^complete$/ : /^(complete|loaded)$/
  97. if (e.type === 'load' || (readyRegExp.test((e.currentTarget || e.srcElement).readyState))) {
  98. config.modules[item] = url;
  99. head.removeChild(node);
  100. (function poll() {
  101. if(++timeout > config.timeout * 1000 / 4){
  102. return error(item + ' is not a valid module');
  103. };
  104. config.status[item] ? onCallback() : setTimeout(poll, 4);
  105. }());
  106. }
  107. }
  108. //回调
  109. function onCallback(){
  110. exports.push(layui[item]);
  111. apps.length > 1 ?
  112. that.use(apps.slice(1), callback, exports)
  113. : ( typeof callback === 'function' && callback.apply(layui, exports) );
  114. }
  115. //如果使用了 layui.all.js
  116. if(apps.length === 0
  117. || (layui['layui.all'] && modules[item])
  118. || (!layui['layui.all'] && layui['layui.mobile'] && modules[item])
  119. ){
  120. return onCallback(), that;
  121. }
  122. //首次加载模块
  123. if(!config.modules[item]){
  124. var node = doc.createElement('script')
  125. ,url = (
  126. modules[item] ? (dir + 'lay/') : (config.base || '')
  127. ) + (that.modules[item] || item) + '.js';
  128. node.async = true;
  129. node.charset = 'utf-8';
  130. node.src = url + function(){
  131. var version = config.version === true
  132. ? (config.v || (new Date()).getTime())
  133. : (config.version||'');
  134. return version ? ('?v=' + version) : '';
  135. }();
  136. head.appendChild(node);
  137. if(node.attachEvent && !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && !isOpera){
  138. node.attachEvent('onreadystatechange', function(e){
  139. onScriptLoad(e, url);
  140. });
  141. } else {
  142. node.addEventListener('load', function(e){
  143. onScriptLoad(e, url);
  144. }, false);
  145. }
  146. config.modules[item] = url;
  147. } else { //缓存
  148. (function poll() {
  149. if(++timeout > config.timeout * 1000 / 4){
  150. return error(item + ' is not a valid module');
  151. };
  152. (typeof config.modules[item] === 'string' && config.status[item])
  153. ? onCallback()
  154. : setTimeout(poll, 4);
  155. }());
  156. }
  157. return that;
  158. };
  159. //获取节点的style属性值
  160. Layui.prototype.getStyle = function(node, name){
  161. var style = node.currentStyle ? node.currentStyle : win.getComputedStyle(node, null);
  162. return style[style.getPropertyValue ? 'getPropertyValue' : 'getAttribute'](name);
  163. };
  164. //css外部加载器
  165. Layui.prototype.link = function(href, fn, cssname){
  166. var that = this
  167. ,link = doc.createElement('link')
  168. ,head = doc.getElementsByTagName('head')[0];
  169. if(typeof fn === 'string') cssname = fn;
  170. var app = (cssname || href).replace(/\.|\//g, '')
  171. ,id = link.id = 'layuicss-'+app
  172. ,timeout = 0;
  173. link.rel = 'stylesheet';
  174. link.href = href + (config.debug ? '?v='+new Date().getTime() : '');
  175. link.media = 'all';
  176. if(!doc.getElementById(id)){
  177. head.appendChild(link);
  178. }
  179. if(typeof fn !== 'function') return that;
  180. //轮询css是否加载完毕
  181. (function poll() {
  182. if(++timeout > config.timeout * 1000 / 100){
  183. return error(href + ' timeout');
  184. };
  185. parseInt(that.getStyle(doc.getElementById(id), 'width')) === 1989 ? function(){
  186. fn();
  187. }() : setTimeout(poll, 100);
  188. }());
  189. return that;
  190. };
  191. //css内部加载器
  192. Layui.prototype.addcss = function(firename, fn, cssname){
  193. return layui.link(config.dir + 'css/' + firename, fn, cssname);
  194. };
  195. //图片预加载
  196. Layui.prototype.img = function(url, callback, error) {
  197. var img = new Image();
  198. img.src = url;
  199. if(img.complete){
  200. return callback(img);
  201. }
  202. img.onload = function(){
  203. img.onload = null;
  204. callback(img);
  205. };
  206. img.onerror = function(e){
  207. img.onerror = null;
  208. error(e);
  209. };
  210. };
  211. //全局配置
  212. Layui.prototype.config = function(options){
  213. options = options || {};
  214. for(var key in options){
  215. config[key] = options[key];
  216. }
  217. return this;
  218. };
  219. //记录全部模块
  220. Layui.prototype.modules = function(){
  221. var clone = {};
  222. for(var o in modules){
  223. clone[o] = modules[o];
  224. }
  225. return clone;
  226. }();
  227. //拓展模块
  228. Layui.prototype.extend = function(options){
  229. var that = this;
  230. //验证模块是否被占用
  231. options = options || {};
  232. for(var o in options){
  233. if(that[o] || that.modules[o]){
  234. error('\u6A21\u5757\u540D '+ o +' \u5DF2\u88AB\u5360\u7528');
  235. } else {
  236. that.modules[o] = options[o];
  237. }
  238. }
  239. return that;
  240. };
  241. //路由解析
  242. Layui.prototype.router = function(hash){
  243. var that = this
  244. ,hash = hash || location.hash
  245. ,data = {
  246. path: []
  247. ,search: {}
  248. ,hash: (hash.match(/[^#](#.*$)/) || [])[1] || ''
  249. };
  250. if(!/^#\//.test(hash)) return data; //禁止非路由规范
  251. hash = hash.replace(/^#\//, '').replace(/([^#])(#.*$)/, '$1').split('/') || [];
  252. //提取Hash结构
  253. that.each(hash, function(index, item){
  254. /^\w+=/.test(item) ? function(){
  255. item = item.split('=');
  256. data.search[item[0]] = item[1];
  257. }() : data.path.push(item);
  258. });
  259. return data;
  260. };
  261. //本地存储
  262. Layui.prototype.data = function(table, settings){
  263. table = table || 'layui';
  264. if(!win.JSON || !win.JSON.parse) return;
  265. //如果settings为null,则删除表
  266. if(settings === null){
  267. return delete localStorage[table];
  268. }
  269. settings = typeof settings === 'object'
  270. ? settings
  271. : {key: settings};
  272. try{
  273. var data = JSON.parse(localStorage[table]);
  274. } catch(e){
  275. var data = {};
  276. }
  277. if(settings.value) data[settings.key] = settings.value;
  278. if(settings.remove) delete data[settings.key];
  279. localStorage[table] = JSON.stringify(data);
  280. return settings.key ? data[settings.key] : data;
  281. };
  282. //设备信息
  283. Layui.prototype.device = function(key){
  284. var agent = navigator.userAgent.toLowerCase()
  285. //获取版本号
  286. ,getVersion = function(label){
  287. var exp = new RegExp(label + '/([^\\s\\_\\-]+)');
  288. label = (agent.match(exp)||[])[1];
  289. return label || false;
  290. }
  291. //返回结果集
  292. ,result = {
  293. os: function(){ //底层操作系统
  294. if(/windows/.test(agent)){
  295. return 'windows';
  296. } else if(/linux/.test(agent)){
  297. return 'linux';
  298. } else if(/iphone|ipod|ipad|ios/.test(agent)){
  299. return 'ios';
  300. } else if(/mac/.test(agent)){
  301. return 'mac';
  302. }
  303. }()
  304. ,ie: function(){ //ie版本
  305. return (!!win.ActiveXObject || "ActiveXObject" in win) ? (
  306. (agent.match(/msie\s(\d+)/) || [])[1] || '11' //由于ie11并没有msie的标识
  307. ) : false;
  308. }()
  309. ,weixin: getVersion('micromessenger') //是否微信
  310. };
  311. //任意的key
  312. if(key && !result[key]){
  313. result[key] = getVersion(key);
  314. }
  315. //移动设备
  316. result.android = /android/.test(agent);
  317. result.ios = result.os === 'ios';
  318. return result;
  319. };
  320. //提示
  321. Layui.prototype.hint = function(){
  322. return {
  323. error: error
  324. }
  325. };
  326. //遍历
  327. Layui.prototype.each = function(obj, fn){
  328. var key
  329. ,that = this;
  330. if(typeof fn !== 'function') return that;
  331. obj = obj || [];
  332. if(obj.constructor === Object){
  333. for(key in obj){
  334. if(fn.call(obj[key], key, obj[key])) break;
  335. }
  336. } else {
  337. for(key = 0; key < obj.length; key++){
  338. if(fn.call(obj[key], key, obj[key])) break;
  339. }
  340. }
  341. return that;
  342. };
  343. //将数组中的对象按其某个成员排序
  344. Layui.prototype.sort = function(obj, key, desc){
  345. var clone = JSON.parse(
  346. JSON.stringify(obj)
  347. );
  348. if(!key) return clone;
  349. //如果是数字,按大小排序,如果是非数字,按字典序排序
  350. clone.sort(function(o1, o2){
  351. var isNum = /^-?\d+$/
  352. ,v1 = o1[key]
  353. ,v2 = o2[key];
  354. if(isNum.test(v1)) v1 = parseFloat(v1);
  355. if(isNum.test(v2)) v2 = parseFloat(v2);
  356. if(v1 && !v2){
  357. return 1;
  358. } else if(!v1 && v2){
  359. return -1;
  360. }
  361. if(v1 > v2){
  362. return 1;
  363. } else if (v1 < v2) {
  364. return -1;
  365. } else {
  366. return 0;
  367. }
  368. });
  369. desc && clone.reverse(); //倒序
  370. return clone;
  371. };
  372. //阻止事件冒泡
  373. Layui.prototype.stope = function(e){
  374. e = e || win.event;
  375. e.stopPropagation
  376. ? e.stopPropagation()
  377. : e.cancelBubble = true;
  378. };
  379. //自定义模块事件
  380. Layui.prototype.onevent = function(modName, events, callback){
  381. if(typeof modName !== 'string'
  382. || typeof callback !== 'function') return this;
  383. config.event[modName + '.' + events] = [callback];
  384. //不再对多次事件监听做支持
  385. /*
  386. config.event[modName + '.' + events]
  387. ? config.event[modName + '.' + events].push(callback)
  388. : config.event[modName + '.' + events] = [callback];
  389. */
  390. return this;
  391. };
  392. //执行自定义模块事件
  393. Layui.prototype.event = function(modName, events, params){
  394. var that = this
  395. ,result = null
  396. ,filter = events.match(/\(.*\)$/)||[] //提取事件过滤器
  397. ,set = (events = modName + '.'+ events).replace(filter, '') //获取事件本体名
  398. ,callback = function(_, item){
  399. var res = item && item.call(that, params);
  400. res === false && result === null && (result = false);
  401. };
  402. layui.each(config.event[set], callback);
  403. filter[0] && layui.each(config.event[events], callback); //执行过滤器中的事件
  404. return result;
  405. };
  406. win.layui = new Layui();
  407. }(window);