PageSourceSearch

https://www.0dx.cn/public/layui/layui.js

js 0dx.cn collected 2026-10-09 04:34:11 UTC 10,971 bytes, 425 lines download raw bytes

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

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.