layui.js 15 KB

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