您的位置:首页 > 产品设计 > UI/UE

模拟mui框架编码

2016-09-06 13:37 316 查看
//调用方法
/*
1、tm.os.ios/tm.os.android/tm.os.versions().webKit //表示安卓设备/ios设备/webKit内核

*/

var tm = (function(document) {
"use strict";
var readyRE = /complete|loaded|interactive/, //complete 可返回浏览器是否已完成对图像的加载。
idSelectorRE = /^#([\w-]+)$/,
$ = function(selector, context) {
context = context || document;
if(!selector)
return wrap();
if(typeof selector === 'object')
if($.isArrayLike(selector)) {
return wrap($.slice.call(selector), null);
} else {
return wrap([selector], null);
}
if(typeof selector === 'function')
return $.ready(selector);
if(typeof selector === 'string') {
try {
selector = selector.trim();
if(idSelectorRE.test(selector)) {
var found = document.getElementById(RegExp.$1);
return wrap(found ? [found] : []);
}
return wrap($.qsa(selector, context), selector);
} catch(e) {}
}
return wrap();
},
wrap = function(dom, selector) {
dom = dom || [];
Object.setPrototypeOf(dom, $.fn);
dom.selector = selector || '';
return dom;
};
/**
* ready(DOMContentLoaded)
* @param {type} callback
* @returns {_L6.$}
*/
$.ready = function(callback) {
if(readyRE.test(document.readyState)) {
callback($);
} else {
document.addEventListener('DOMContentLoaded', function() {
callback($);
}, false);
}
return this;
};
/**
* zui querySelectorAll
* @param {type} selector
* @param {type} context
* @returns {Array}
*/
$.qsa = function(selector, context) {
context = context || document;
return $.slice.call(classSelectorRE.test(selector) ? context.getElementsByClassName(RegExp.$1) : tagSelectorRE.test(selector) ? context.getElementsByTagName(selector) : context.querySelectorAll(selector));
};
/**
* zui slice(array)
*/
$.slice = [].slice;
/**
* zui isArrayLike
* @param {Object} obj
*/
$.isArrayLike = function(obj) {
var length = !!obj && "length" in obj && obj.length;
var type = $.type(obj);
if(type === "function" || $.isWindow(obj)) {
return false;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && (length - 1) in obj;
};
$.type = function(obj) {
return obj == null ? String(obj) : class2type[{}.toString.call(obj)] || "object";
};
/**
* $.fn
*/
$.fn = {
each: function(callback) {
[].every.call(this, function(el, idx) {
return callback.call(el, idx, el) !== false;
});
return this;
}
};
/**
* isWindow(需考虑obj为undefined的情况)
*/
$.isWindow = function(obj) {
return obj != null && obj === obj.window;
};
/**
* $.cd
*/
$.cd = {
"KEYCODE": "TmCred16",
"HEXTO": "1234567890ABCDEF"
};
return $;
})(document);


实现模块拆分

/**
* 判断设备类型,及其版本号
* @param {Object} $
* @param {Object} window
*/
(function($, window) {
"use strict";
function detect(ua) {
this.os = {};
var funcs = [

function() { //wechat
var wechat = ua.match(/(MicroMessenger)\/([\d\.]+)/i);
if(wechat) { //wechat
this.os.wechat = {
version: wechat[2].replace(/_/g, '.')
};
}
return false;
},
function() { //android
var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
if(android) {
this.os.android = true;
this.os.version = android[2];

this.os.isBadAndroid = !(/Chrome\/\d/.test(window.navigator.appVersion));
}
return this.os.android === true;
},
function() { //ios
var iphone = ua.match(/(iPhone\sOS)\s([\d_]+)/);
if(iphone) { //iphone
this.os.ios = this.os.iphone = true;
this.os.version = iphone[2].replace(/_/g, '.');
} else {
var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
if(ipad) { //ipad
this.os.ios = this.os.ipad = true;
this.os.version = ipad[2].replace(/_/g, '.');
}
}
return this.os.ios === true;
}
];
[].every.call(funcs, function(func) {
return !func.call($);
});
$.os.versions = function(ua) { //其他版本
return {
trident: ua.indexOf('Trident') > -1, //IE内核
presto: ua.indexOf('Presto') > -1, //opera内核
webKit: ua.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
gecko: ua.indexOf('Gecko') > -1 && ua.indexOf('KHTML') == -1, //火狐内核
mobile: !!ua.match(/AppleWebKit.*Mobile.*/) || !!ua.match(/AppleWebKit/), //是否为移动终端
ios: !!ua.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
android: ua.indexOf('Android') > -1 || ua.indexOf('Linux') > -1, //android终端或者uc浏览器
iPhone: ua.indexOf('iPhone') > -1 || ua.indexOf('Mac') > -1, //是否为iPhone或者安卓QQ浏览器
iPad: ua.indexOf('iPad') > -1, //是否为iPad
webApp: ua.indexOf('Safari') == -1, //是否为web应用程序,没有头部与底部
weixin: ua.indexOf('MicroMessenger') == -1 //是否为微信浏览器
};
};
}
detect.call($, navigator.userAgent);
})(tm, window);


/**
* fixed trim 前后空格用空字符串替代。
* @param {type} undefined
* @returns {undefined}
*/
(function(undefined) {
"use strict";
if(String.prototype.trim === undefined) { // fix for iOS 3.2
String.prototype.trim = function() {
//用正则表达式将前后空格用空字符串替代。
return this.replace(/^\s+|\s+$/g, '');
};
}
Object.setPrototypeOf = Object.setPrototypeOf || function(obj, proto) {
obj['__proto__'] = proto;
return obj;
};
})();

/*
A shim for non ES5 supporting browsers.
Adds function bind to Function prototype, so that you can do partial application.
Works even with the nasty thing, where the first word is the opposite of extranet, the second one is the profession of Columbus, and the version number is 9, flipped 180 degrees.
*/

Function.prototype.bind = Function.prototype.bind || function(to) {
// Make an array of our arguments, starting from second argument
var partial = Array.prototype.splice.call(arguments, 1),
// We'll need the original function.
fn = this;
var bound = function() {
// Join the already applied arguments to the now called ones (after converting to an array again).
var args = partial.concat(Array.prototype.splice.call(arguments, 0));
// If not being called as a constructor
if(!(this instanceof bound)) {
// return the result of the function called bound to target and partially applied.
return fn.apply(to, args);
}
// If being called as a constructor, apply the function bound to self.
fn.apply(this, args);
}
// Attach the prototype of the function to our newly created function.
bound.prototype = fn.prototype;
return bound;
};

/**
* fixed classList
* @param {type} document
* @returns {undefined}
*/
(function(document) {
"use strict";
if(!("classList" in document.documentElement) && Object.defineProperty && typeof HTMLElement !== 'undefined') {

Object.defineProperty(HTMLElement.prototype, 'classList', {
get: function() {
var self = this;

function update(fn) {
return function(value) {
var classes = self.className.split(/\s+/),
index = classes.indexOf(value);

fn(classes, index, value);
self.className = classes.join(" ");
};
}

var ret = {
add: update(function(classes, index, value) {
~index || classes.push(value);
}),
remove: update(function(classes, index) {
~index && classes.splice(index, 1);
}),
toggle: update(function(classes, index, value) {
~index ? classes.splice(index, 1) : classes.push(value);
}),
contains: function(value) {
return !!~self.className.split(/\s+/).indexOf(value);
},
item: function(i) {
return self.className.split(/\s+/)[i] || null;
}
};

Object.defineProperty(ret, 'length', {
get: function() {
return self.className.split(/\s+/).length;
}
});

return ret;
}
});
}
})(document);

/**
* fixed requestAnimationFrame
* @param {type} window
* @returns {undefined}
*/
(function(window) {
"use strict";
if(!window.requestAnimationFrame) {
var lastTime = 0;
window.requestAnimationFrame = window.webkitRequestAnimationFrame || function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16.7 - (currTime - lastTime));
var id = window.setTimeout(function() {
callback(currTime + timeToCall);
}, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
window.cancelAnimationFrame = window.webkitCancelAnimationFrame || window.webkitCancelRequestAnimationFrame || function(id) {
clearTimeout(id);
};
};
}(window));

/**
* 弹幕
* @param {Object} tm
* @param {Object} Zepto
*/
(function(tm, $) {
"use strict";
tm.popTip = function(con, col, time) {
col = col ? col : 'white';
time = time ? time : 2000;
if($("#alertdiv").html() == null) {
var val = "<div id='alertdiv' style='height:auto; background:rgba(0,0,0,0.7); border-radius:13px; position:absolute; z-index:1000; box-shadow:2px 2px 10 #000; line-height:38px;text-align:center;font-size:16px;color:" + col + "; max-width:400px; padding:10px 25px; '>" + con + "</div>";
var newelement = $(val);
$('body').append(newelement);
var dis1 = $("#alertdiv").width();
dis1 = parseInt(dis1);
var dis2 = dis1 + 0;
var dis3 = $(window).width();
var dis4 = (dis3 - dis2) / 2;
$('#alertdiv').css('margin-left', dis4 + 'px');
$('#alertdiv').animate({
'display': 'block'
}, time, function() {
$(this).remove();
});
}
var windowHeight = $(window).height();
var scrollHeight = $(window).scrollTop();
if(scrollHeight != 0) {
var discenter = windowHeight / 100 * 40;
var disall = scrollHeight + discenter;
$('#alertdiv').css('top', disall + 'px');
} else {
$('#alertdiv').css('top', '40%');
}
}
})(tm, Zepto);

/**
日期,包括日子转换之类的东西
* @param {type} $
* @returns {undefined}
*/
(function($) {
/*
对Date的扩展,将 Date 转化为指定格式的String
月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
例子:
(new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
(new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
*/
Date.prototype.Format = function(fmt) { //author: y
var o = {
"M+": this.getMonth() + 1, //月份
"d+": this.getDate(), //日
"h+": this.getHours(), //小时
"m+": this.getMinutes(), //分
"s+": this.getSeconds(), //秒
"q+": Math.floor((this.getMonth() + 3) / 3), //季度
"S": this.getMilliseconds() //毫秒
};
if(/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for(var k in o)
if(new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
}
})(tm);

/**
*  工具类
* @param {Object} $
*/
(function($) {
//字符串格式
$.gt = {};
$.gt.GetQueryString = function(name) { //通过参数名获取URL传递的参数值(正则表达式)
"use strict";
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i"),
r = window.location.search.substr(1).match(reg);
if(r != null)
return(r[2]);
return null;
};
//数组格式
$.gt.GetRequest = function() {
"use strict";
var url = location.search || location.href; //获取url中"?"符后的字串
var theRequest = new Object();
if(url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for(var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
}
}
return theRequest;
};
//生成6位数的单号
$.gt.generateMixed = function() {
"use strict";
var Num = "";
for(var i = 0; i < 6; i++) {
Num += Math.floor(Math.random() * 10);
}
return Num;
};
/**
* utf16转utf8
* @param {Object} str
*/
$.gt.utf16to8 = function(str) {
"use strict";
var out, i, len, c;
out = "";
len = str.length;
for(i = 0; i < len; i++) {
c = str.charCodeAt(i);
if((c >= 0x0001) && (c <= 0x007F)) {
out += str.charAt(i);
} else
if(c > 0x07FF) {
out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
} else {
out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
}
}
return out;
};
/**
* utf8转utf16
* @param {Object} str
*/
$.gt.utf8to16 = function(str) {
"use strict";
var out, i, len, c;
var char2, char3;
out = "";
len = str.length;
i = 0;
while(i < len) {
c = str.charCodeAt(i++);
switch(c >> 4) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
// 0xxxxxxx
out += str.charAt(i - 1);
break;
case 12:
case 13:
// 110x xxxx 10xx xxxx
char2 = str.charCodeAt(i++);
out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
break;
case 14:
// 1110 xxxx10xx xxxx10xx xxxx
char2 = str.charCodeAt(i++);
char3 = str.charCodeAt(i++);
out += String.fromCharCode(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | ((char3 & 0x3F) << 0));
break;
}
}
return out;
};
/**
* 万、亿,转换
*/
$.gt.formatUnit = function(data) {
"use strict";
if(!data) {
return "";
}
var r = "";
if(data.length < 5) {
r = data;
} else if(data.length > 4 && data.length < 9) {
r = (data / 10000).toFixed(2) + "万";
} else if(data.length >= 9) {
r = (data / 100000000).toFixed(2) + "亿";
}
return r;
};
/**
* 检查网速是否联网
*/
$.gt.onLine = function(){
"use strict";
if (navigator.onLine)
return true;
//执行离线状态时的任务
return false;
}
})(tm);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  框架