layui.js 13 KB

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