layui.js 15 KB

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