layui.js

/*!

@Title: Layui
@Description:經(jīng)典模塊化前端框架
@Site: www.layui.com
@Author: 賢心
@License:MIT

*/

;!function(win) {

"use strict";

var Lay = function() {
    this.v = '1.0.9_rls'; //版本號
};

Lay.fn = Lay.prototype;

var doc = document,
    config = Lay.fn.cache = {},

    // 獲取本js所在目錄
    getPath = function() {
        var js = doc.scripts,
            jsPath = js[js.length - 1].src;
        return jsPath.substring(0, jsPath.lastIndexOf('/') + 1);
    }(),

    // 異常提示
    error = function(msg) {
        win.console && console.error && console.error('Layui hint: ' + msg);
    },

    // 檢測opera環(huán)境
    isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',

    // 內(nèi)置模塊
    modules = {
        layer : 'modules/layer', //彈層
        laydate : 'modules/laydate', //日期
        laypage : 'modules/laypage', //分頁
        laytpl : 'modules/laytpl', //模板引擎
        layim : 'modules/layim', //web通訊
        layedit : 'modules/layedit', //富文本編輯器
        form : 'modules/form', //表單集
        upload : 'modules/upload', //上傳
        tree : 'modules/tree', //樹結(jié)構(gòu)
        table : 'modules/table', //富表格
        element : 'modules/element', //常用元素操作
        util : 'modules/util', //工具塊
        flow : 'modules/flow', //流加載
        carousel : 'modules/carousel', //輪播
        code : 'modules/code', //代碼修飾器
        jquery : 'modules/jquery', //DOM庫(第三方)  
        mobile : 'modules/mobile', //移動大模塊 | 若當(dāng)前為開發(fā)目錄,則為移動模塊入口,否則為移動模塊集合
        'layui.all' : 'dest/layui.all' //PC模塊合并版
    };

config.modules = {}; //記錄模塊物理路徑
config.status = {}; // 記錄已注冊的模塊集。
config.timeout = 10; //符合規(guī)范的模塊請求最長等待秒數(shù)
config.event = {}; //記錄模塊自定義事件

// 定義模塊
Lay.fn.define = function(deps, callback) {
    var that = this,
        type = typeof deps === 'function',
        mods = function() {
            // 參數(shù)callback,可選,用于回調(diào)。
            // 回調(diào)參數(shù)function,用于回調(diào)時,注冊模塊。
            typeof callback === 'function' && callback(function(app, exports) {
                // 回調(diào)參數(shù)function的參數(shù)app,必要,代表模塊名。
                // 回調(diào)參數(shù)function的參數(shù)exports,必要,代表模塊的接口方法。
                layui[app] = exports;
                // config.status,記錄已注冊的模塊集。
                config.status[app] = true;
            });
            return this;
        };

    // 參數(shù)deps,代表依賴的模塊集,可選。
    type && (
        callback = deps,
        deps = []
    );

    // 相當(dāng)于layui['layui.all'] || layui['layui.mobile']
    // 模塊名layui.all,代表所有模塊。
    // 模塊名layui.mobile,代表手機版的所有模塊。
    // 如果已經(jīng)加載所有模塊,則直接執(zhí)行回調(diào)。
    if (layui['layui.all'] || (!layui['layui.all'] && layui['layui.mobile'])) {
        return mods.call(that);
    }

    // 方法layui.use,動態(tài)加載所依賴的模塊集deps。
    that.use(deps, mods);
    return that;
};

// 動態(tài)加載模塊集
Lay.fn.use = function(apps, callback, exports) {
    var that = this,
    // config.dir,內(nèi)置文件的基目錄,默認(rèn)值為layui.js的所在目錄,需以斜杠結(jié)束。
        dir = config.dir = config.dir ? config.dir : getPath;
    var head = doc.getElementsByTagName('head')[0];

    // 參數(shù)apps,必要,可以是字符串或數(shù)組。
    apps = typeof apps === 'string' ? [ apps ] : apps;

    // 參數(shù)apps中存在jquery時,如果頁面已加載jQuery1.7+庫,則直接使用該庫。
    if (window.jQuery && jQuery.fn.on) {
        that.each(apps, function(index, item) {
            if (item === 'jquery') {
                apps.splice(index, 1);
            }
        });
        layui.jquery = jQuery;
    }

    var item = apps[0],
        timeout = 0;
    // 參數(shù)exports,可選。
    exports = exports || [];

    // config.host,格式為“//.../”,默認(rèn)值為config.dir中的主機,或當(dāng)前頁面的主機。
    config.host = config.host || (dir.match(/\/\/([\s\S]+?)\//)/* 匹配“//.../” */ || [ '//' + location.host + '/' ])[0];

    // apps.length === 0 || (layui['layui.all'] || layui['layui.mobile']) && modules[item]
    // 參數(shù)apps,允許為空集。
    // 如果需要加載的模塊集為空集,則執(zhí)行回調(diào)。
    // 模塊名layui.all,代表所有模塊。
    // 模塊名layui.mobile,代表手機版的所有模塊。
    // modules,代表layui的內(nèi)置模塊集。
    // 如果已經(jīng)加載所有模塊,并且當(dāng)前模塊是layui的內(nèi)置模塊,則當(dāng)前模塊不需要加載。
    if (apps.length === 0
        || (layui['layui.all'] && modules[item])
        || (!layui['layui.all'] && layui['layui.mobile'] && modules[item])
    ) {
        return onCallback(), that;
    }

    // 用于監(jiān)聽文件加載完畢
    function onScriptLoad(e, url) {
        var readyRegExp = navigator.platform === 'PLaySTATION 3' ? /^complete$/ : /^(complete|loaded)$/
        if (e.type === 'load' || (readyRegExp.test((e.currentTarget || e.srcElement).readyState))) {
            config.modules[item] = url;
            head.removeChild(node);
            // 輪詢查看當(dāng)前模塊是否已注冊,每0.025秒輪詢一次,共論詢config.timeout秒。
            // config.timeout,文件加載超時,默認(rèn)值為10秒。
            (function poll() {
                if (++timeout > config.timeout * 1000 / 4) {
                    return error(item + ' is not a valid module');
                };
                config.status[item] ? onCallback() : setTimeout(poll, 4);
            }());
        }
    }

    var node = doc.createElement('script'),
    // config.base,代表擴展模塊的JS文件目錄,默認(rèn)值為空串,需要以斜杠結(jié)束。
    // modules,代表layui的內(nèi)置模塊集。
    // layui.modules[name],代表模塊name的相對路徑(不包括后綴.js),默認(rèn)值為name。
    //         如果當(dāng)前模塊是內(nèi)置模塊,則相對路徑相對于config.dir + "lay/"。
    //        如果當(dāng)前模塊是擴展模塊,則相對路徑相對于config.base。
        url = (modules[item] ? (dir + 'lay/') : (config.base || '')) + (that.modules[item] || item) + '.js';
    node.async = true;
    node.charset = 'utf-8';
    node.src = url + function() {
        // config.version=true時,使用config.v作為版本號,否則自己作為版本號,默認(rèn)值不啟用版本號。
        // config.v,代表版本號,默認(rèn)值為當(dāng)前時間。
        // config.version=true,config.v不設(shè)置時,使流覽器不會加載緩存文件,而是重新加載。
        var version = config.version === true ? (config.v || (new Date()).getTime()) : (config.version || '');
        return version ? ('?v=' + version) : '';
    }();

    // config.modules[name],代表已加載,或正在加載中的模塊name的相對路徑(不包括后綴.js)。
    if (!config.modules[item]) {
        head.appendChild(node);
        if (node.attachEvent && !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && !isOpera) {
            node.attachEvent('onreadystatechange', function(e) {
                onScriptLoad(e, url);
            });
        } else {
            node.addEventListener('load', function(e) {
                onScriptLoad(e, url);
            }, false);
        }
    } else {
        // 輪詢查看是否加載完畢,每0.025秒輪詢一次,共論詢config.timeout秒。
        // config.timeout,文件加載超時,默認(rèn)值為10秒。
        (function poll() {
            if (++timeout > config.timeout * 1000 / 4) {
                return error(item + ' is not a valid module');
            };
            // config.status,記錄已注冊的模塊集。
            (typeof config.modules[item] === 'string' && config.status[item]) ? onCallback() : setTimeout(poll, 4);
        }());
    }
    config.modules[item] = url;

    //回調(diào)
    function onCallback() {
        // 參數(shù)exports,記錄模塊的接口。
        exports.push(layui[item]);
        // 加載下一個模塊,如果沒有下一個,則執(zhí)行回調(diào)。
        apps.length > 1 ? that.use(apps.slice(1), callback, exports) : (typeof callback === 'function' && callback.apply(layui, exports));
    }

    return that;

};

// 獲取節(jié)點的style屬性值
Lay.fn.getStyle = function(node, name) {
    var style = node.currentStyle ? node.currentStyle : win.getComputedStyle(node, null);
    return style[style.getPropertyValue ? 'getPropertyValue' : 'getAttribute'](name);
};

// 動態(tài)加載CSS
Lay.fn.link = function(href, fn, cssname) {
    var that = this,
        link = doc.createElement('link');
    var head = doc.getElementsByTagName('head')[0];
    
    // 參數(shù)fn,可選。
    if (typeof fn === 'string')
        cssname = fn;
    
    // 參數(shù)cssname,用于標(biāo)識CSS文件的ID,默認(rèn)值為href。
    var app = (cssname || href).replace(/\.|\//g, '');
    var id = link.id = 'layuicss-' + app,
        timeout = 0;

    link.rel = 'stylesheet';
    // config.debug=true時,使流覽器不會加載緩存文件。
    link.href = href + (config.debug ? '?v=' + new Date().getTime() : '');
    link.media = 'all';

    // 參數(shù)cssname,同一ID的CSS文件的只許加載一次。
    if (!doc.getElementById(id)) {
        head.appendChild(link);
    }

    // 參數(shù)fn,用于監(jiān)聽CSS加載完畢。
    if (typeof fn !== 'function') return;
    // 輪詢查看是否加載完畢,每0.1秒輪詢一次,共論詢config.timeout秒。
    (function poll() {
        if (++timeout > config.timeout * 1000 / 100) {
            return error(href + ' timeout');
        };
        parseInt(that.getStyle(doc.getElementById(id), 'width')) === 1989 ? function() {
            fn();
        }() : setTimeout(poll, 100);
    }());
};

// css內(nèi)部加載器
Lay.fn.addcss = function(firename, fn, cssname) {
    // 全局配置dir,用于內(nèi)置文件的基目錄,默認(rèn)值為layui.js所在的目錄,需要以斜杠結(jié)束。
    layui.link(config.dir + 'css/' + firename, fn, cssname);
};

// 圖片預(yù)加載
Lay.fn.img = function(url, callback, error) {
    var img = new Image();
    img.src = url;
    if (img.complete) {
        return callback(img);
    }
    img.onload = function() {
        img.onload = null;
        callback(img);
    };
    img.onerror = function(e) {
        img.onerror = null;
        error(e);
    };
};

// 全局配置
Lay.fn.config = function(options) {
    options = options || {};
    for (var key in options) {
        config[key] = options[key];
    }
    return this;
};

// layui.modules[name],代表模塊name的相對路徑(不包括后綴.js),默認(rèn)值為name。
Lay.fn.modules = function() {
    var clone = {};
    for (var o in modules) {
        clone[o] = modules[o];
    }
    return clone;
}();

// 設(shè)置模塊的相對路徑(不含后綴.js)
Lay.fn.extend = function(options) {
    var that = this;

    options = options || {};
    for (var o in options) {
        // layui[name],如果存在,則表示模塊name已注冊。
        // layui.modules[name],代表模塊name的相對路徑(不包括后綴.js),默認(rèn)值為name。
        // 已注冊或已設(shè)置相對路徑的模塊集,不允許再設(shè)置相對路徑。顯然,內(nèi)置模塊的相對路徑不允許更改。
        if (that[o] || that.modules[o]) {
            error('\u6A21\u5757\u540D ' + o + ' \u5DF2\u88AB\u5360\u7528');
        } else {
            that.modules[o] = options[o];
        }
    }
    return that;
};

// 路由
Lay.fn.router = function(hash) {
    var hashs = (hash || location.hash).replace(/^#/, '').split('/') || [];
    var item,
        param = {
            dir : []
        };
    for (var i = 0; i < hashs.length; i++) {
        item = hashs[i].split('=');
        /^\w+=/.test(hashs[i]) ? function() {
            if (item[0] !== 'dir') {
                param[item[0]] = item[1];
            }
        }() : param.dir.push(hashs[i]);
        item = null;
    }
    return param;
};

// 本地存儲
Lay.fn.data = function(table, settings) {
    table = table || 'layui';

    if (!win.JSON || !win.JSON.parse) return;

    //如果settings為null,則刪除表
    if (settings === null) {
        return delete localStorage[table];
    }

    settings = typeof settings === 'object'
        ? settings
        : {
            key : settings
        };

    try {
        var data = JSON.parse(localStorage[table]);
    } catch (e) {
        var data = {};
    }

    if (settings.value)
        data[settings.key] = settings.value;
    if (settings.remove)
        delete data[settings.key];
    localStorage[table] = JSON.stringify(data);

    return settings.key ? data[settings.key] : data;
};

// 設(shè)備信息
Lay.fn.device = function(key) {
    var agent = navigator.userAgent.toLowerCase();

    //獲取版本號
    var getVersion = function(label) {
        var exp = new RegExp(label + '/([^\\s\\_\\-]+)');
        label = (agent.match(exp) || [])[1];
        return label || false;
    };

    var result = {
        os : function() { //底層操作系統(tǒng)
            if (/windows/.test(agent)) {
                return 'windows';
            } else if (/linux/.test(agent)) {
                return 'linux';
            } else if (/iphone|ipod|ipad|ios/.test(agent)) {
                return 'ios';
            }
        }(),
        ie : function() { //ie版本
            return (!!win.ActiveXObject || "ActiveXObject" in win) ? (
                (agent.match(/msie\s(\d+)/) || [])[1] || '11' //由于ie11并沒有msie的標(biāo)識
                ) : false;
        }(),
        weixin : getVersion('micromessenger') //是否微信
    };

    //任意的key
    if (key && !result[key]) {
        result[key] = getVersion(key);
    }

    //移動設(shè)備
    result.android = /android/.test(agent);
    result.ios = result.os === 'ios';

    return result;
};

// 提示
Lay.fn.hint = function() {
    return {
        error : error
    }
};

// 遍歷
Lay.fn.each = function(obj, fn) {
    var that = this,
        key;
    if (typeof fn !== 'function') return that;
    obj = obj || [];
    if (obj.constructor === Object) {
        for (key in obj) {
            if (fn.call(obj[key], key, obj[key])) break;
        }
    } else {
        for (key = 0; key < obj.length; key++) {
            if (fn.call(obj[key], key, obj[key])) break;
        }
    }
    return that;
};

// 阻止事件冒泡
Lay.fn.stope = function(e) {
    e = e || win.event;
    e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;
};

// 自定義模塊事件
Lay.fn.onevent = function(modName, events, callback) {
    if (typeof modName !== 'string'
        || typeof callback !== 'function') return this;
    config.event[modName + '.' + events] = [ callback ];

    //不再對多次事件監(jiān)聽做支持
    /*
    config.event[modName + '.' + events] 
      ? config.event[modName + '.' + events].push(callback) 
    : config.event[modName + '.' + events] = [callback];
    */

    return this;
};

// 執(zhí)行自定義模塊事件
Lay.fn.event = function(modName, events, params) {
    var that = this,
        result = null,
        filter = events.match(/\(.*\)$/) || []; //提取事件過濾器
    var set = (events = modName + '.' + events).replace(filter, ''); //獲取事件本體名
    var callback = function(_, item) {
        var res = item && item.call(that, params);
        res === false && result === null && (result = false);
    };
    layui.each(config.event[set], callback);
    filter[0] && layui.each(config.event[events], callback); //執(zhí)行過濾器中的事件
    return result;
};

win.layui = new Lay();

}(window);

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,224評論 25 708
  • **2014真題Directions:Read the following text. Choose the be...
    又是夜半驚坐起閱讀 11,173評論 0 23
  • 在現(xiàn)實中,經(jīng)常會有人在痛心,我與她是真心相愛,我喜歡她,她也有表示她喜歡我,可為什么,我們還是感覺不到在一起...
    殤斷閱讀 295評論 0 2
  • 結(jié)婚,終身大事,爹不疼娘不愛,不聞不問。 工作,高不成低不就。 關(guān)上門,都是不開心,沒有未來,沒有安全感,連訴說的...
    淺話閱讀 278評論 0 0
  • 以前 我不信佛 不信主 不信天堂 這些荒唐的謬論 不過是 信徒用來自欺欺人以逃避風(fēng)塵瑣碎的借口 我自作聰明地 表示...
    馬麓閱讀 205評論 0 0

友情鏈接更多精彩內(nèi)容