layui.js 15 KB

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