/**
* MyJs
* Version: 0.4.8.31beta
* 参考:http://www.Comojs.com/
* date: 2011-11-23
* 说明:0.4.2beta 新增了弹出框MessageBox封装
* 0.4.3beta 新增了验证支持
* 0.4.4beta 修改了几个bug
* 0.4.5beta 修改了ajax 正在加载bug
* 0.4.6beta 修改了验证提示在输入的下方,并解决多浏览器验证先后问题。例如验证为空和数字,前后顺序颠倒导致提示错误
* 0.4.7beta 将控件相关分离出来
* 0.4.8beta 修改dom top left 的bug
* 0.4.8.1beta 修改children的bug
* 0.4.8.21beta 修改top left 的返回为null bug
* 0.4.8.22beta 修改ajax 跨域访问问题 bug
* 0.4.8.23beta 添加时间差函数dateDiff
* 0.4.8.24beta 修改验证控件错误显示位置bug
* 0.4.8.25beta 添加截取字符串函数leftAddDot dateDiff
* 0.4.8.26beta formatDateTime 添加参数为null情况的处理
* 0.4.8.27beta 修改dateDiff的时间差bug
* 0.4.8.28beta 添加getRootPath 获得网站根路径的方法
* 0.4.8.29beta 修正验证控件
* 0.4.8.30beta 修正验证控件不支持ie9问题 问题原因 IE>=9 下时要使用标准浏览器的方法 dispatchEvent(不支持fireEvent方法) 并增加验证身份证号码合法功能isIdCard
* 0.4.8.31beta formatDateTime 添加参数为 0001-01-01 00:00:00情况的处理
*/
/************************************************ MyJs ****************************************************/
var MyJs = function (_id) {
var _obj = document.getElementById(_id) ? document.getElementById(_id) : _id;
if (_obj) {
_obj = _obj ? [_obj] : [];
MyJs.Object.extend(_obj, _myjs_prototype);
return _obj;
}
return null;
};
MyJs.version = "0.4.8.29beta";
var _myjs_prototype = {
type: function () {//dom类型
return this[0].type;
},
size: function () {
return this.length;
},
getId: function () {
return this[0].id;
},
attr: function (name, value) {
if (typeof (value) == 'undefined') {
var el = this[0];
switch (name) {
case 'class':
return el.className;
case 'style':
return el.style.cssText;
default:
return el.getAttribute(name);
}
} else {
this.each(function (el) {
el = el[0];
switch (name) {
case 'class':
el.className = value;
break;
case 'style':
el.style.cssText = value;
break;
default:
el.setAttribute(name, value);
}
});
return this;
}
},
css: function (name, value) {
if (typeof (value) == 'undefined') {
var el = this[0];
if (name == 'opacity') {
if (MyJs.Browser.ie) {
return el.filter && el.filter.indexOf("opacity=") >= 0 ? parseFloat(el.filter.match(/opacity=([^)]*)/)[1]) / 100 : 1;
} else {
return el.style.opacity ? parseFloat(el.style.opacity) : 1;
}
} else {
function hyphenate(name) {
return name.replace(/[A-Z]/g,
function (match) {
return '-' + match.toLowerCase();
});
}
if (window.getComputedStyle) {
return window.getComputedStyle(el, null).getPropertyValue(hyphenate(name));
}
if (document.defaultView && document.defaultView.getComputedStyle) {
var computedStyle = document.defaultView.getComputedStyle(el, null);
if (computedStyle) return computedStyle.getPropertyValue(hyphenate(name));
if (name == "display") return "none";
}
if (el.currentStyle) {
return el.currentStyle[name];
}
return el.style[name];
}
} else {
this.each(function (el) {
el = el[0];
if (name == 'opacity') {
if (MyJs.Browser.ie) {
el.style.filter = 'Alpha(Opacity=' + value * 100 + ');';
el.style.zoom = 1;
} else {
el.style.opacity = (value == 1 ? '' : '' + value);
}
} else {
if (typeof value == 'number') value += 'px';
el.style[name] = value;
}
});
return this;
}
},
each: function (callback) {
for (var i = 0, il = this.length; i < il; i++) {
if (callback(MyJs(this[i]), i) == 'break') break;
}
return this;
},
prop: function (name, value) {
if (typeof (value) === 'undefined') {
return this[0][name];
} else {
this.each(function (el) {
if (value == null) {
el[0][name] = "";
} else {
el[0][name] = value;
}
});
return this;
}
},
inject: function (el) {
el = MyJs(el);
if (el) el.append(this);
return this;
},
append: function () {
var args = arguments;
this.each(function (it) {
for (var i = 0, il = args.length; i < il; i++) {
MyJs.insert(it[0], args[i], 3);
}
});
return this;
},
prepend: function () {
var args = arguments;
this.each(function (it) {
for (var i = args.length - 1; i >= 0; i--) {
MyJs.insert(it[0], args[i], 2);
}
});
return this;
},
before: function () {
var args = arguments;
this.each(function (it) {
for (var i = 0, il = args.length; i < il; i++) {
MyJs.insert(it[0], args[i], 1);
}
});
return this;
},
after: function () {
var args = arguments;
this.each(function (it) {
for (var i = args.length - 1; i >= 0; i--) {
MyJs.insert(it[0], args[i], 4);
}
});
return this;
},
remove: function () {
this.each(function (el) {
el[0].parentNode.removeChild(el[0]);
});
return this;
},
text: function (value) {
return this.prop(typeof (this[0].innerText) != 'undefined' ? 'innerText' : 'textContent', value);
},
html: function (value) {
return this.prop('innerHTML', value);
},
val: function (value) {
var el = this[0];
if (typeof (value) === 'undefined') {
if (el.tagName.toLowerCase() == 'input') {
switch (el.type) {
case 'checkbox':
return el.checked ? true : false;
break;
case 'radio':
return el.checked ? true : false;
break;
}
}
return el.value;
} else {
switch (el.type) {
case 'checkbox':
{
if (value == "checked" || value == "yes") { value = true; }
if (value == "unchecked" || value == "no") { value = false; }
return this.prop('checked', value); break;
}
case 'radio':
{
if (value == "checked" || value == "yes") { value = true; }
if (value == "unchecked" || value == "no") { value = false; }
return this.prop('checked', value); break;
}
default: return this.prop('value', value);
}
}
},
left: function (value) {
if (typeof (value) == 'undefined') {
return parseInt(this[0].style.left) || 0;
} else {
this.each(function (el) {
el[0].style.left = value + 'px';
});
}
return this;
},
top: function (value) {
if (typeof (value) == 'undefined') {
return parseInt(this[0].style.top) || 0;
} else {
this.each(function (el) {
el[0].style.top = value + 'px';
});
}
return this;
},
pos: function () {//获取绝对位置
var el = this[0], left = 0, top = 0;
left = el.offsetLeft;
top = el.offsetTop;
var target = el.offsetParent;
while (target) {
left += target.offsetLeft;
top += target.offsetTop;
target = target.offsetParent;
}
return { left: left, top: top, x: left, y: top };
},
height: function (value) {
if (typeof (value) == 'undefined') {
var el = this[0];
if (el == window) {
return document.documentElement.clientHeight;
}
return el.offsetHeight || (el.style.height ? parseInt(el.style.height.replace('px', '')) : 0);
} else {
return this.css('height', value + 'px');
}
},
width: function (value) {
if (typeof (value) == 'undefined') {
var el = this[0];
if (el == window) {
return document.documentElement.clientWidth;
}
return el.offsetWidth || (el.style.width ? parseInt(el.style.width.replace('px', '')) : 0);
} else {
return this.css('width', value + 'px');
}
},
show: function (val) {
this.css('display', typeof val === 'undefined' ? 'block' : val);
return this;
},
hide: function () {
this.css('display', 'none');
return this;
},
focus: function () {
this[0].focus();
return this;
},
hasClass: function (name) {
if (name && this[0].className) {
return new RegExp('\\b' + MyJs.String.trim(name) + '\\b').test(this[0].className);
}
return false;
},
addClass: function (name) {
this.each(function (it) {
it = it[0];
var arr = [];
if (it.className) {
arr = it.className.split(' ');
if (!MyJs.Array.include(arr, name)) arr.push(name);
} else {
arr.push(name);
}
it.className = arr.join(' ');
});
return this;
},
removeClass: function (name) {
this.each(function (it) {
it = it[0];
if (it.className) {
var regexp = new RegExp('\\b' + MyJs.String.trim(name) + '\\b', 'g');
it.className = it.className.replace(regexp, '');
}
});
return this;
},
removeAttr: function (name) {
this.each(function (it) {
it[0].removeAttribute(name);
});
return this;
},
//name: eg. backgroundColor
removeCSS: function (name) {
if (!name) {
this.removeAttr('style');
return this;
}
this.each(function (it) {
var s = it[0].style;
if (s.removeAttribute) {
s.removeAttribute(name);
} else {
name = name.replace(/([A-Z])/g, function (v) {
return '-' + v.toLowerCase();
});
s.removeProperty(name);
}
});
return this;
},
simulate: function (name) {
this.each(function (el) {
MyJs.Event.simulate(el[0], name);
});
return this;
},
on: function (name, fun) {
MyJs.Event.on(this[0], name, fun);
return this;
},
un: function (name, fun) {
MyJs.Event.un(this[0], name, fun);
return this;
},
click: function (fn) {
this.on('click', fn);
},
prev: function (n) {
n = n || 0;
var el = this[0], r, i = 0;
while ((el = el.previousSibling)) {
if (el.nodeType && el.nodeType == 1) {
r = el;
if (i == n) break;
i++;
}
}
return r ? MyJs(r) : null;
},
prevAll: function () {
var els = [], el = this[0];
while ((el = el.previousSibling)) {
if (el.nodeType && el.nodeType == 1) {
els = _onlyPush(els, el);
}
}
return MyJs(els);
},
next: function (n) {
n = n || 0;
var el = this[0], r, i = 0;
while ((el = el.nextSibling)) {
if (el.nodeType && el.nodeType == 1) {
r = el;
if (i == n) break;
i++;
}
}
return r ? MyJs(r) : null;
},
nextAll: function () {
var els = [], el = this[0];
while ((el = el.nextSibling)) {
if (el.nodeType && el.nodeType == 1) {
els = _onlyPush(els, el);
}
}
return MyJs(els);
},
first: function () {
var els = this.children();
return els ? MyJs(this.children()[0]) : null;
},
last: function () {
var els = this.children();
return els ? MyJs(els[els.length - 1]) : null;
},
children: function (n) {
var nodes = this[0].childNodes, els = [], it;
for (var i = 0, il = nodes.length; i < il; i++) {
it = nodes[i];
if (it.nodeType && it.nodeType == 1)
els = _onlyPush(els, MyJs(it));
}
return typeof n != 'undefined' ? els.get(n) : els;
},
parent: function (n) {
var el = this[0];
n = n || 0;
for (var i = 0; i < n + 1; i++) {
el = el.parentNode;
}
return MyJs(el);
},
/**
* 绑定select控件
*@param _jsonObj: json数据集
*@param _text: 显示字段
*@param _value: 值字段
*@return:true or false
*@throws 这个方法所抛出的异常
*/
bind: function (_jsonObj, _sText, _sValue) {
var _objSel = this[0];
_objSel.options.length = 0;
if (_sText == null || _sValue == null) { return false; }
if (_jsonObj.length == 0 || _jsonObj == "") {
_objSel.options[0] = new Option('===无===', '-1', 0, 0);
} else {
for (var i = 0, l = _jsonObj.length; i < l; i++) {
_objSel.options[i] = new Option(_jsonObj[i][_sText], _jsonObj[i][_sValue], 0, 0);
}
}
},
_isInit: 0, //是否初始化提示
isNotNull: function () {//判断控件值是否为空
this.Validation("Presence"); return this;
},
isNumeral: function (config) {//判断控件值是否为数字
this.Validation("Numericality", config || {}); return this;
},
isIdCard: function () {//判断控件值是否为身份证号码格式
this.Validation("IdCard"); return this;
},
isEmail: function () {//判断控件值是否为Email格式
this.Validation("Email"); return this;
},
isLength: function (config) {//判断控件值的长度
this.Validation("Length", config); return this;
},
//验证控件相关
//Text1.Validation(Validate.Presence);//不为空
//Text1.Validation(Validate.Length,{minimum:3,maxmum:6});
//Text1.Validation(Validate.Numericality,{onlyInteger:true});
//Text1.Validation(Validate.Numericality,{maxmum:500});
Validation: function (type, config) {//验证类型 Presence,Numericality,Length
var el = this;
var elts = MyJs("__Validation_" + el[0].id);
MyJs._ValidationObjs.push(el);
var op = MyJs.Object.extend({
onlyInteger: null,
minimum: null,
maxmum: null
}, config || {});
var showError = function (_str) {
el.css("border", "solid 1px #f00");
MyJs("__ValidationOK_" + el[0].id).html("0");
elts.html(_str).show();
};
var showRight = function (){
if (MyJs("__ValidationOK_" + el[0].id).html() == "0") { return; }
el.css("border", "solid 1px #999");
elts.html("").hide();
};
var _Presence = function () {//验证是否为空
if (el.val().isNull()) {
showError("不为空");
} else {
showRight();
}
};
var _Length = function () {//验证字符长度
if (el.val() == "") {
showRight();
return;
}
if (op.minimum !== null) {
if (el.val().byteLength() < op.minimum) {
showError("不能小于" + op.minimum + "个字符");
return;
}
}
if (op.maxmum !== null) {
if (el.val().byteLength() > op.maxmum) {
showError("不能大于" + op.maxmum + "个字符");
return;
}
}
showRight();
};
//isIdCard
var _IdCard = function () {//验证身份证号码
if (el.val() == "") {
showRight();
return;
}
if (!el.val().IsIdCard()) {
showError("身份证号码不合法");
} else {
showRight();
}
};
var _Email = function () {//验证邮件地址
if (el.val() == "") {
showRight();
return;
}
if (!el.val().isEmail()) {
showError("邮件格式错误");
} else {
showRight();
}
};
var _Numericality = function () {//验证数字
if (el.val() == "") {
showRight();
return;
}
if (op.onlyInteger == true) {
if (!el.val().isInteger()) {
showError("必须为整数");
return;
}
} else if (!el.val().IsNum()) {
showError("必须为数字");
return;
}
if (op.minimum !== null) {
if (parseFloat(el.val()) < op.minimum) {
showError("不能小于" + op.minimum);
return;
}
}
if (op.maxmum !== null) {
if (parseFloat(el.val()) > op.maxmum) {
showError("不能大于" + op.maxmum);
return;
}
}
showRight();
};
if (0 == this._isInit) {
this._isInit = 1;
el.after("<div style=\"color:#f00; position:absolute;z-index:2000;display:block;\" id=\"__Validation_" + el[0].id + "\"></div>");
el.after("<span id=\"__ValidationOK_" + el[0].id + "\" style=\"display:none;\">1</span>");
elts.left(el.pos().left + el.width());
elts.top(el.pos().top);
MyJs.Event.on(el[0], 'keyup', function () { MyJs("__ValidationOK_" + el[0].id).html('1'); });
MyJs.Event.on(el[0], 'blur', function () { MyJs("__ValidationOK_" + el[0].id).html('1'); });
}
switch (type) {
case "Presence":
{
elts.html("*");
MyJs.Event.on(el[0], 'keyup', _Presence);
MyJs.Event.on(el[0], 'blur', _Presence);
break;
}
case "Length":
{
MyJs.Event.on(el[0], 'keyup', _Length);
MyJs.Event.on(el[0], 'blur', _Length);
break;
}
case "Email":
{
MyJs.Event.on(el[0], 'keyup', _Email);
MyJs.Event.on(el[0], 'blur', _Email);
break;
}
case "IdCard":
{
MyJs.Event.on(el[0], 'keyup', _IdCard);
MyJs.Event.on(el[0], 'blur', _IdCard);
break;
}
case "Numericality":
{
MyJs.Event.on(el[0], 'keyup', _Numericality);
MyJs.Event.on(el[0], 'blur', _Numericality);
break;
}
}
return this;
}
};
Validate = {
Presence: 'Presence', //不允许空
Numericality: 'Numericality', //验证数字
Length: 'Length', //验证长度
Email: 'Email', //邮箱地址
Email: 'IdCard' //身份证号码
};
MyJs._ValidationObjs = new Array(); //记录所有需验证控件列表
//触发所有需验证控件 返回是否所有控件都符合验证 true or false 例如 οnsubmit="return $.fireAllValidation();"
MyJs.fireAllValidation = function () {
MyJs._ValidationObjs.unique();
var _tmpOK = true;
MyJs._ValidationObjs.each(function (_obj) {
_obj.simulate("blur");
if (_tmpOK) {
var _tmpStr = $("__Validation_" + _obj[0].id).html();
if (_tmpStr != "" && _tmpStr != "√") {
_tmpOK = false;
_obj.focus();
}
}
});
return _tmpOK;
};
/************************************************** Object *******************************************************/
MyJs.Object = {
/*
* extend object
*/
extend: function (target, src) {
for (var it in src) {
target[it] = src[it];
}
return target;
},
/*
* loop object
*/
each: function (obj, cb) {
var i = 0;
for (var it in obj) {
if (cb(obj[it], it, i++) == 'break') break;
}
return obj;
},
/*
* clone object fully
*/
clone: function (obj) {
var con = obj.constructor, cloneObj = null;
if (con == Object) {
cloneObj = new con();
} else if (con == Function) {
return MyJs.Function.clone(obj);
} else cloneObj = new con(obj.valueOf());
for (var it in obj) {
if (cloneObj[it] != obj[it]) {
if (typeof (obj[it]) != 'object') {
cloneObj[it] = obj[it];
} else {
cloneObj[it] = arguments.callee(obj[it])
}
}
}
cloneObj.toString = obj.toString;
cloneObj.valueOf = obj.valueOf;
return cloneObj;
},
/*
* Object to String 将某个对象转化为字符串(Json标准格式)
*/
toStr: function (obj) {
try {
if (obj instanceof Array) {
var r = [];
for (var i = 0; i < obj.length; i++)
r.push(arguments.callee(obj[i]));
return "[" + r.join() + "]";
} else if (typeof obj == 'string') {
return "\"" + obj.replace("\"", "'").replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
} else if (typeof obj == 'number') {
return obj.toString();
} else if (typeof obj == 'object') {
if (obj == null) {
return '';
} else {
var r = [];
for (var i in obj)
r.push("\"" + i + "\":" + arguments.callee(obj[i]));
return "{" + r.join() + "}";
}
} else if (typeof obj == 'boolean') {
return obj + '';
} else if (typeof obj == 'function') {
return obj.toString();
} else {
return '';
}
} catch (e) {
return '';
}
}
};
/************************************************** Class *******************************************************/
MyJs.Class = {
/*
* create a class, and setup constructor
*/
create: function () {
var f = function () {
this.initialize.apply(this, arguments);
};
for (var i = 0, il = arguments.length, it; i < il; i++) {
it = arguments[i];
if (it == null) continue;
MyJs.Object.extend(f.prototype, it);
}
return f;
},
/*
* inherit a class, and not support multiple
*/
inherit: function (superC, opt) {
function temp() { };
temp.prototype = superC.prototype;
var f = function () {
this.initialize.apply(this, arguments);
};
f.prototype = new temp();
MyJs.Object.extend(f.prototype, opt);
f.prototype.superClass_ = superC.prototype;
f.prototype.super_ = function () {
this.superClass_.initialize.apply(this, arguments);
};
return f;
}
};
MyJs.createElement = function (name, obj) {
var el = MyJs(document.createElement(name));
if (obj) {
for (var i in obj) {
el.attr(i, obj[i]);
}
}
return el;
};
/************************************************** String *******************************************************/
MyJs.String = {
//remove space of head and end [去字符串前后空格]
trim: function (str) {
return str.replace(/^\s+|\s+$/g, '');
},
lTrim: function (str) {//remove space of head [去字符串前空格]
return str.replace(/(^\s*)/g, "");
},
rTrim: function (str) {//remove space of end [去字符串后空格]
return str.replace(/(\s*$)/g, "");
},
IsNum: function (str) {//判断是否为数字
if (str != null && str != "") { return !isNaN(str); } return false;
},
isInteger: function (str) {//是否为整数
var re = /^-?\d+$/;
if (re.test(str)) {
return true;
} return false;
},
isEmail: function (str) {
var re = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
if (re.test(str)) {
return true;
} return false;
},
//判断字符为空
isNull: function (str) {
if (str.byteLength() < 1) {
return true;
} else {
return false;
}
},
//判断身份证号码
IsIdCard : function(number){
number = number.toLowerCase();
var date, Ai;
var verify = "10x98765432";
var Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
var area = ['','','','','','','','','','','','北京','天津','河北','山西','内蒙古','','','','','','辽宁','吉林','黑龙江','','','','','','','','上海','江苏','浙江','安微','福建','江西','山东','','','','河南','湖北','湖南','广东','广西','海南','','','','重庆','四川','贵州','云南','西藏','','','','','','','陕西','甘肃','青海','宁夏','新疆','','','','','','台湾','','','','','','','','','','香港','澳门','','','','','','','','','国外'];
var re = number.match(/^(\d{2})\d{4}(((\d{2})(\d{2})(\d{2})(\d{3}))|((\d{4})(\d{2})(\d{2})(\d{3}[x\d])))$/i);
if(re == null) return false;
if(re[1] >= area.length || area[re[1]] == "") return false;
if(re[2].length == 12){
Ai = number.substr(0, 17);
date = [re[9], re[10], re[11]].join("-");
}
else{
Ai = number.substr(0, 6) + "19" + number.substr(6);
date = ["19" + re[4], re[5], re[6]].join("-");
}
if(!this.IsDate(date, "ymd")) return false;
var sum = 0;
for(var i = 0;i<=16;i++){
sum += Ai.charAt(i) * Wi[i];
}
Ai += verify.charAt(sum%11);
return (number.length ==15 || number.length == 18 && number == Ai);
},
//判断日期合法
IsDate: function (op, formatString) {
formatString = formatString || "ymd";
var m, year, month, day;
switch(formatString){
case "ymd" :
m = op.match(new RegExp("^((\\d{4})|(\\d{2}))([-./])(\\d{1,2})\\4(\\d{1,2})$"));
if(m == null ) return false;
day = m[6];
month = m[5]*1;
year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3], 10));
break;
case "dmy" :
m = op.match(new RegExp("^(\\d{1,2})([-./])(\\d{1,2})\\2((\\d{4})|(\\d{2}))$"));
if(m == null ) return false;
day = m[1];
month = m[3]*1;
year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6], 10));
break;
default :
break;
}
if(!parseInt(month)) return false;
month = month==0 ?12:month;
var date = new Date(year, month-1, day);
return (typeof(date) == "object" && year == date.getFullYear() && month == (date.getMonth()+1) && day == date.getDate());
function GetFullYear(y){return ((y<30 ? "20" : "19") + y)|0;}
},
/**
* 字符串转换为json对象
* @obj {string} json字符串
*/
toJson: function (str) {
return eval('(' + str + ')');
},
escapeHTML: function (str) {//escapeHTML
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
},
unescapeHTML: function (str) {//unescapeHTML
return str.replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&');
},
byteLength: function (str) {//get the string's length, a Chinese char is two lengths
return str.replace(/[^\x00-\xff]/g, "**").length;
},
delLast: function (str) {//remove the last char
return str.substring(0, str.length - 1);
},
toInt: function (str) {//String to Int
return Math.floor(str);
},
toArray: function (str, o) {//String to Array
return str.split(o || '');
},
toDate: function (str) {//String to Date
return new Date(str.replace(/[-]/g, '/'));
},
//substring, start from head, and a Chinese char is two lengths
left: function (str, n) {
if (str == null) return "";
var s = str.replace(/\*/g, " ").replace(/[^\x00-\xff]/g, "**");
s = s.slice(0, n).replace(/\*\*/g, " ").replace(/\*/g, "").length;
return str.slice(0, s);
},
//截取字符串,如果有截取则加 ...
leftAddDot: function (str, n) {
if (str == null) return "";
var s = str.replace(/\*/g, " ").replace(/[^\x00-\xff]/g, "**");
s = s.slice(0, n).replace(/\*\*/g, " ").replace(/\*/g, "").length;
if (str.length <= s) {
return str;
} else {
return str.slice(0, s) + "...";
}
},
//substring, start from end, and a Chinese char is two lengths
right: function (str, n) {
var len = str.length;
var s = str.replace(/\*/g, " ").replace(/[^\x00-\xff]/g, "**");
s = s.slice(s.length - n, s.length).replace(/\*\*/g, " ").replace(/\*/g, "").length;
return str.slice(len - s, len);
},
//remove HTML tags
removeHTML: function (str) {
return str.replace(/<\/?[^>]+>/gi, '');
},
//format string
//eg. "<div>{0}</div>{1}".format(txt0,txt1);
format: function () {
var str = arguments[0], args = [];
for (var i = 1, il = arguments.length; i < il; i++) {
args.push(arguments[i]);
}
return str.replace(/\{(\d+)\}/g, function (m, i) {
return args[i];
});
},
// toLowerCase
toLower: function (str) {
return str.toLowerCase();
},
// toUpperCase
toUpper: function (str) {
return str.toUpperCase();
},
// toString(16)
on16: function (str) {
var a = [], i = 0;
for (; i < str.length; ) a[i] = ("00" + str.charCodeAt(i++).toString(16)).slice(-4);
return "\\u" + a.join("\\u");
},
// unString(16)
un16: function (str) {
return unescape(str.replace(/\\/g, "%"));
},
/**
* 时间字符串的格式化显示;
* @dateTime {string} 要格式化的日期字符串
* @format {string} 格式化字符 可为空
*/
formatDateTime: function (str, f) {
if (str == null) { return ""; }
if (str == "0001-01-01 00:00:00") { return ""; }
if (str == "") { return ""; }
if (!f || f == "") { f = "yyyy-MM-dd"; }
var myDate = new Date(str.replace(/[-]/g, '/'));
return MyJs.Date.format(myDate, f); //格式化时间
},
escape: function (str) {
return escape(str);
},
unescape: function (str) {
return unescape(str);
},
alert: function (str) {
alert(str);
}
};
/************************************************** Date *******************************************************/
MyJs.Date = {
//eg. new Date().format('yyyy-MM-dd');
format: function (date, f) {
if (!f || f == "") { f = "yyyy-MM-dd"; }
var o = {
"M+": date.getMonth() + 1,
"d+": date.getDate(),
"h+": date.getHours(),
"m+": date.getMinutes(),
"s+": date.getSeconds(),
"q+": Math.floor((date.getMonth() + 3) / 3),
"S": date.getMilliseconds()
};
if (/(y+)/.test(f))
f = f.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var k in o)
if (new RegExp("(" + k + ")").test(f))
f = f.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
return f;
},
//获取时间差
//_type :D表示查询精确到天数的之差
//_type :H表示查询精确到小时之差
//_type :M表示查询精确到分钟之差
//_type :S表示查询精确到秒之差
//_type :T表示查询精确到毫秒之差
//使用方法:
//dateDiff('2007-4-1', '2007/04/19','D');
dateDiff: function (date1, date2, _type) {
_type = _type.toUpperCase();
var _tmp = 1;
switch (_type) {
case "D": { _tmp = 1000 * 60 * 60 * 24; break; }
case "H": { _tmp = 1000 * 60 * 60; break; }
case "M": { _tmp = 1000 * 60; break; }
case "S": { _tmp = 1000; break; }
case "T": { _tmp = 1; break; }
default: { _tmp = 1000; break; }
}
var dt1 = new Date(Date.parse(date1.replace(/-/g, '/')));
var dt2 = new Date(Date.parse(date2.replace(/-/g, '/')));
try {
return Math.round((dt2.getTime() - dt1.getTime()) / _tmp);
}
catch (e) {
}
},
//添加年
addYear: function (date, num) {
return this.add(date, 'yy', num);
},
//添加月
addMonth: function (date, num) {
return this.add(date, 'mm', num);
},
//添加日
addDay: function (date, num) {
return this.add(date, 'dd', num);
},
/**
* 累加时间
* @date {date} 要格式化的日期字符串
* @part {string} 时间部分 yy表示年 qq季度 mm月 wk星期 dd日 hh小时 mi分钟 ss秒 ms毫秒
* @num {int|string} 格式化字符 可为空
*/
add: function (date, part, num) {
var datecopy;
var ms = date.getTime();
num = parseInt(num);
switch (part) {
case "ms":
ms += num;
break;
case "ss":
ms += 1000 * num;
break;
case "mi":
ms += 60 * 1000 * num;
break;
case "hh":
ms += 60 * 60 * 1000 * num;
break;
case "dd":
ms += 24 * 60 * 60 * 1000 * num;
break;
case "wk":
ms += 7 * 24 * 60 * 60 * 1000 * num;
break;
case "mm":
datecopy = new Date(Date.parse(date));
datecopy.setFullYear(date.getFullYear() + Math.floor((date.getMonth() + num) / 12));
var mth = (date.getMonth() + num) % 12;
if (mth < 0) mth += 12;
datecopy.setMonth(mth);
break;
case "qq":
datecopy = new Date(Date.parse(date));
datecopy.setFullYear(date.getFullYear() + Math.floor((date.getMonth() + 3 * num) / 12));
var mth = (date.getMonth() + 3 * num) % 12;
if (mth < 0) mth += 12;
datecopy.setMonth(mth);
break;
case "yy":
datecopy = new Date(Date.parse(date));
datecopy.setFullYear(date.getFullYear() + num);
break;
}
if (datecopy == null)
return new Date(ms);
else
return datecopy;
}
};
/************************************************* Function *****************************************************/
MyJs.Function = {
//设置该方法延迟一定时间后执行,单位毫秒 例如test.timeout(1000)//1秒钟后执行 只执行一次
timeout: function (fun, time) {
return setTimeout(fun, time);
},
//设置该方法间隔一定时间执行一次,单位毫秒
interval: function (fun, time) {
return setInterval(fun, time);
},
//apply scope, and can transfer some arguments [设置方法新的作用域(this),并且在新方法的所有参数之前插入一些参数]
bind: function (fun) {
var _this = arguments[1], args = [];
for (var i = 2, il = arguments.length; i < il; i++) {
args.push(arguments[i]);
}
return function () {
var thisArgs = args.concat();
for (var i = 0, il = arguments.length; i < il; i++) {
thisArgs.push(arguments[i]);
}
return fun.apply(_this || this, thisArgs);
}
},
//apply scope, and transfer event and some ohter arguments
bindEvent: function (fun) {
var _this = arguments[1], args = [];
for (var i = 2, il = arguments.length; i < il; i++) {
args.push(arguments[i]);
}
return function (e) {
var thisArgs = args.concat();
thisArgs.unshift(e || window.event);
return fun.apply(_this || this, thisArgs);
}
},
//clone function
clone: function (fun) {
var clone = function () {
return fun.apply(this, arguments);
};
clone.prototype = fun.prototype;
for (prototype in fun) {
if (fun.hasOwnProperty(prototype) && prototype != 'prototype') {
clone[prototype] = fun[prototype];
}
}
return clone;
}
};
/************************************************* Cookie ******************************************************/
MyJs.Cookie = {
get: function (name) {
var v = document.cookie.match('(?:^|;)\\s*' + name + '=([^;]*)');
return v ? decodeURIComponent(v[1]) : null;
},
//MyJs.Cookie.set(name, value);
//MyJs.Cookie.set(name, value, expires); //expires=0过期时间为永不过期,expires=1为1分钟,expires = null ? '' 过期时间为浏览器关闭时间
//MyJs.Cookie.set(name, value, expires, path, domain);
set: function (name, value, expires, path, domain) {
var str = name + "=" + encodeURIComponent(value);
if (expires != null || expires != '') {
if (expires == 0) { expires = 100 * 365 * 24 * 60; }
var exp = new Date();
exp.setTime(exp.getTime() + expires * 60 * 1000);
str += "; expires=" + exp.toGMTString();
}
if (path) { str += "; path=" + path; }
if (domain) { str += "; domain=" + domain; }
document.cookie = str;
},
del: function (name, path, domain) {
document.cookie = name + "=" +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
};
/************************************************** Array *******************************************************/
MyJs.Array = {
_each: function (arr, ca, collect, only) {
var r = [];
for (var i = 0, il = arr.length; i < il; i++) {
var v = ca(arr[i], i);
if (collect && typeof (v) != 'undefined') {
if (only) {
r = _onlyPush(r, v);
} else {
r.push(v);
}
} else {
if (!collect && v == 'break') break;
}
}
return r;
},
//循环数组并执行
each: function (arr, ca) {
this._each(arr, ca, false);
return this;
},
//循环数组,并执行后返回新的数组
collect: function (arr, ca, only) {
return this._each(arr, ca, true, only);
},
//whether an Array include th value or object [检查数组是否包含某个值]
include: function (arr, value) {
return this.index(arr, value) != -1;
},
//take the index that the value in an Array [返回某个值在数组的位置]
index: function (arr, value) {
for (var i = 0, il = arr.length; i < il; i++) {
if (arr[i] == value) return i;
}
return -1;
},
//unique [删除数组中的重复项]
unique: function (arr) {
if (arr.length && typeof (arr[0]) == 'object') {
var len = arr.length;
for (var i = 0, il = len; i < il; i++) {
var it = arr[i];
for (var j = len - 1; j > i; j--) {
if (arr[j] == it) arr.splice(j, 1);
}
}
return arr;
} else {
var result = [], hash = {};
for (var i = 0, key; (key = arr[i]) != null; i++) {
if (!hash[key]) {
result.push(key);
hash[key] = true;
}
}
return result;
}
},
//remove the item [删除数组中的某个值,参数支持值和数组位置]
remove: function (arr, o) {
if (typeof o == 'number' && !MyJs.Array.include(arr, o)) {
arr.splice(o, 1);
} else {
var i = MyJs.Array.index(arr, o);
if (i > -1) arr.splice(i, 1);
}
return arr;
},
removeAll: function (arr) {
arr.length = 0;
return arr;
},
//take a random item [随机取数组中的任意一项]
random: function (arr) {
var i = Math.round(Math.random() * (arr.length - 1));
return arr[i];
},
//将array转换为字符串
toStr: function (arr) {
return Object.toStr(arr);
}
};
/************************************************* Ajax ******************************************************/
/**
* Ajax方法 该方法只适用于同步请求
*@param url: url路径 参数可放在这里也可放在para里。
*@param para: 传递参数 可为空, 不为空时 通过sent传值,可避ie下免传参数过多导致失败 参考:http://gbtan.iteye.com/blog/653314
*@return:json数据集或{"success":"false"}
*@demo:
1、var oJson = Ajax.post("abc.aspx?id=3");
2、var oJson = Ajax.post("abc.aspx","id=3");
*/
MyJs.post = function (url, para) {
try {
var _para = para || null;
var NewXml;
if (window.ActiveXObject) {
try { NewXml = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {
try { NewXml = new ActiveXObject("msxml2.XMLHTTP"); }
catch (ex) { }
}
} else if (window.XMLHttpRequest) {
NewXml = new XMLHttpRequest();
}
NewXml.open("POST", url, false);
NewXml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
NewXml.onreadystatechange = function () {
if (NewXml.readyState == 4) {
if (NewXml.status == 200) {
} else if (NewXml.status == 404) {
alert("Request URL does not exist");
} else {
alert("Error: status code is " + NewXml.status);
}
}
};
NewXml.send(_para);
return eval('(' + NewXml.responseText + ')');
}
catch (e) {
//alert(e.message);alert(e.description);alert(e.number);alert(e.name);
return { "success": "false" }
}
};
//跨域执行ajax请求 返回
MyJs.GetJsonp = function (config) {
config.type = "jsonp";
MyJs.Ajax.ajax(config);
};
//执行ajax请求 返回格式为json
MyJs.GetJson = function (config) {
config.type = "json";
MyJs.Ajax.ajax(config);
};
//执行ajax请求 返回格式为xml
MyJs.GetXml = function (config) {
config.type = "xml";
MyJs.Ajax.ajax(config);
};
//执行ajax请求,返回XMLHttpRequest对象
//MyJs.Ajax({
// url : 'http://www.sina.com.cn/xxx.jsp', //[必须]
// type : 'json', //text or xml or json(默认) or jsonp(跨域调用json,需要后台支持)
// method : 'get', //请求方式,post,get(默认)
// encode: 'UTF-8', //请求的编码, UTF-8(默认)
// async: true, //是否异步,false(默认)
// param: null, //参数 object || string
// success : function(info){
// alert(info);
// },
// failure : function(error){
// alert(errow);
// },
// whatever : function(){
// }
//});
MyJs.Ajax = {
ajax: function (config) {
if (document.getElementById("_div_loging") == null) {
var _div_loging = document.createElement("div");
_div_loging.innerHTML = "正在加载...";
_div_loging.id = "_div_loging";
_div_loging.style.cssText = "width:74px; height:18px; color:#fff; font-size:15px; position:absolute; top:0px; right:0px; background:#D14244";
document.body.appendChild(_div_loging);
}
var op = MyJs.Object.extend({
url: null,
method: 'get',
async: false,
param: null,
type: 'json',
encode: 'UTF-8',
success: function () { },
failure: function () { },
whatever: function () { }
}, config || {});
op.method = (op.type == 'jsonp') ? 'GET' : op.method.toUpperCase() || 'GET';
if (typeof window._$JSON_callback == 'undefined') {
window._$JSON_callback = {};
}
this._createRequest(op);
},
_createRequest: function (_op) {
return (_op.type == 'jsonp') ? this._setJSONPRequest(_op) : this._setXHRRequest(_op);
},
_setXHRRequest: function (_opt) {
var param = '';
if (typeof (_opt.param) == 'string') {
param = _opt.param;
} else {
for (var i in _opt.param) {
if (param == '') {
param = i + '=' + _opt.param[i];
} else {
param += '&' + i + '=' + _opt.param[i];
}
}
}
if (_opt.method == 'GET' && param.trim() != '') {
_opt.url += (_opt.url.indexOf('?') == -1 ? '?' : '&') + param;
param = null;
}
var _XHR = this._createXHR();
_XHR.onreadystatechange = function () {
var tmp = "";
if (_XHR.readyState == 4) {
if (_XHR.status == 200) {
if (document.getElementById("_div_loging")) {
document.body.removeChild(document.getElementById("_div_loging"));
}
switch (_opt.type) {
case 'text':
tmp = _XHR.responseText;
break;
case 'json':
tmp = eval('(' + _XHR.responseText + ')');
break;
case 'xml':
tmp = _XHR.responseXML;
break;
}
_opt.success(tmp);
} else {
_opt.failure("{success:false,'msg':\"Error: status code is " + _XHR.status + "\"}");
}
if (_opt.whatever) _opt.whatever(_XHR);
}
};
_XHR.open(_opt.method, _opt.url, _opt.async);
if (_opt.method == 'POST') {
_XHR.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=" + _opt.encode);
};
_XHR.send(param || null);
},
_createXHR: function () {
var methods = [
function () { return new XMLHttpRequest(); },
function () { return new ActiveXObject('Msxml2.XMLHTTP'); },
function () { return new ActiveXObject('Microsoft.XMLHTTP'); }
];
for (var i = 0, l = methods.length; i < l; i++) {
try {
methods[i]();
} catch (e) {
continue;
}
this._createXHR = methods[i];
return methods[i]();
}
},
// 建立JSONP请求
_setJSONPRequest: function (_opt) {
var fun = this._setRandomFun();
window._$JSON_callback[fun.id] = function (data) {
_opt.success(data);
};
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
var _url = '';
var param = '';
if (typeof (_opt.param) == 'string') {
param += "&" + _opt.param;
} else {
for (var i in _opt.param) {
param += '&' + i + '=' + _opt.param[i];
}
}
var _indexT = _opt.url.indexOf('?');
if (_indexT == -1) {
_url = _opt.url + "?" + param + '&callback=' + fun.name;
} else {
param += "&" + _opt.url.right(_opt.url.byteLength() - _indexT - 1);
_url = _opt.url.left(_indexT) + "?" + param + '&callback=' + fun.name;
}
script.type = 'text/javascript';
script.charset = 'utf-8';
if (head) {
head.appendChild(script);
} else {
document.body.appendChild(script);
}
if (MyJs.Browser.ie) { //IE6+
setTimeout(function () {
document.body.removeChild(document.getElementById("_div_loging"));
delete window._$JSON_callback[fun.id];
script.parentNode.removeChild(script);
}, 100);
} else {
script.onload = function () {
document.body.removeChild(document.getElementById("_div_loging"));
delete window._$JSON_callback[fun.id];
script.parentNode.removeChild(script);
}
}
script.src = _url;
},
// 生成随机JSON回调函数
_setRandomFun: function () {
var id = '';
do {
id = '$JSON' + Math.floor(Math.random() * 10000);
} while (window._$JSON_callback[id])
return {
id: id,
name: 'window._$JSON_callback.' + id
}
}
};
/************************************************* Other ******************************************************/
MyJs.extend = function (options) {
MyJs.Object.extend(MyJs, options);
};
MyJs.extend({
insert: function (elem, content, where) {
var doit = function (el, value) {
switch (where) {
case 1:
{
el.parentNode.insertBefore(value, el);
break;
}
case 2:
{
el.insertBefore(value, el.firstChild);
break;
}
case 3:
{
if (el.tagName.toLowerCase() == 'table' && value.tagName.toLowerCase() == 'tr') {
if (el.tBodies.length == 0) {
el.appendChild(document.createElement('tbody'));
}
el.tBodies[0].appendChild(value);
} else {
el.appendChild(value);
}
break;
}
case 4:
{
el.parentNode.insertBefore(value, el.nextSibling);
break;
}
}
};
where = where || 1;
if (typeof (content) == 'object') {
if (content.size) {
if (where == 2) content = content.reverse();
MyJs.Array.each(content, function (it) {
doit(elem, it);
});
} else {
doit(elem, content);
}
} else {
if (typeof (content) == 'string') {
var div = document.createElement('div');
div.innerHTML = content;
var childs = div.childNodes;
var nodes = [];
for (var i = childs.length - 1; i >= 0; i--) {
nodes.push(div.removeChild(childs[i]));
}
nodes = nodes.reverse();
for (var i = 0, il = nodes.length; i < il; i++) {
doit(elem, nodes[i]);
}
}
}
return this;
},
isFunction: function (fn) {
return !!fn && typeof fn != "string" && !fn.nodeName && fn.constructor != Array && /^[\s[]?function/.test(fn + "");
},
log: function (str) {
if (typeof console != 'undefined' && console.log)
console.log(str);
},
error: function (msg) {
if (typeof console !== "undefined" && console.error)
console.error(msg);
}
});
/*
* (c)2006 Jesse Skinner/Dean Edwards/Matthias Miller/John Resig
* Special thanks to Dan Webb's domready.js Prototype extension
* and Simon Willison's addLoadEvent
*
* For more info, see:
* http://www.thefutureoftheweb.com/blog/adddomloadevent
* http://dean.edwards.name/weblog/2006/06/again/
* http://www.vivabit.com/bollocks/2006/06/21/a-dom-ready-extension-for-prototype
* http://simon.incutio.com/archive/2004/05/26/addLoadEvent
*
*
* To use: call addDOMLoadEvent one or more times with functions, ie:
*
* function something() {
* // do something
* }
* addDOMLoadEvent(something);
*
* addDOMLoadEvent(function() {
* // do other stuff
* });
*
*/
MyJs.addDOMLoadEvent = (function () {
// create event function stack
var load_events = [],
load_timer,
script,
done,
exec,
old_onload,
init = function () {
done = true;
// kill the timer
clearInterval(load_timer);
// execute each function in the stack in the order they were added
while (exec = load_events.shift())
exec();
if (script) script.onreadystatechange = '';
};
return function (func) {
// if the init function was already ran, just run this function now and stop
if (done) return func();
if (!load_events[0]) {
// for Mozilla/Opera9
if (document.addEventListener)
document.addEventListener("DOMContentLoaded", init, false);
// for Internet Explorer
/*@cc_on@*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=//0><\/scr" + "ipt>");
script = document.getElementById("__ie_onload");
script.onreadystatechange = function () {
if (this.readyState == "complete")
init(); // call the onload handler
};
/*@end@*/
// for Safari
if (/WebKit/i.test(navigator.userAgent)) { // sniff
load_timer = setInterval(function () {
if (/loaded|complete/.test(document.readyState))
init(); // call the onload handler
}, 10);
}
// for other browsers set the window.onload, but also execute the old window.onload
old_onload = window.onload;
window.onload = function () {
init();
if (old_onload) old_onload();
};
}
load_events.push(func);
}
})();
/************************************************* Event ******************************************************/
MyJs.Event = {
/*add custom event to the Object
Params: obj(event target), names(event name锛孉rray of String), [options](option)
options: {
onListener: { //when is listened
"walk" : function(){} //when the walk event is listened, fire the function
}
}
*/
custom: function (obj, names, options) {
var ce = obj._customEvents = {};
for (var i = 0, il = names.length; i < il; i++) {
ce[names[i]] = [];
}
if (options) {
if (options.onListener) {
ce._onListener = options.onListener;
}
}
var bind = MyJs.Function.bind;
obj.on = bind(this._customOn, this, obj);
obj.un = bind(this._customUn, this, obj);
obj.fire = bind(this._customFire, this, obj);
return obj;
},
_customOn: function (obj, name, listener) {
var ce = obj._customEvents;
if (!ce || !ce[name]) return;
ce[name].push(listener);
if (ce._onListener && ce._onListener[name]) {
var f = ce._onListener[name];
if (MyJs.isFunction(f)) f(obj, name, listener);
}
return this;
},
_customUn: function (obj, name, listener) {
var ce = obj._customEvents;
if (!ce || !ce[name]) return;
MyJs.Array.remove(ce[name], listener);
return this;
},
//fire event
_customFire: function (obj, name, data) {
var ce = obj._customEvents;
if (!ce || !ce[name]) return;
var ces = ce[name], e = {
type: name, //浜嬩欢鍚�
srcElement: obj, //浜嬩欢婧�
data: data, //浼犻€掑€�
isStop: false, //褰撳墠浜嬩欢鏄惁鍋滄浼犻€�
stop: function () { this.isStop = true; } //鍋滄浜嬩欢浼犻€掔粰涓嬩竴涓狶istener
};
for (var i = 0, il = ces.length; i < il; i++) {
if (!e.isStop) ces[i](e);
}
return this;
},
//simulate user to fire event 模拟用户触发一个事件
//例如:MyJs.Event.simulate(el, 'click'); //触发Dom元素el上的click事件;
simulate: function (el, ename) {
if (!el) return;
if (el.MyJs) el = el[0];
//
// if (MyJs.Browser.ie) {
// var evt = document.createEventObject();
// el.fireEvent("on" + ename, evt);
// } else if (document.createEvent) {
// var ev = document.createEvent('HTMLEvents');
// ev.initEvent(ename, false, true);
// el.dispatchEvent(ev);
// }
if (document.dispatchEvent) {
// 标准浏览器使用dispatchEvent方法
var evt = document.createEvent('HTMLEvents');
// initEvent接受3个参数:
// 事件类型,是否冒泡,是否阻止浏览器的默认行为
evt.initEvent(ename, true, true);
el.dispatchEvent(evt);
}
else {
// IE浏览器支持fireEvent方法
var evt = document.createEventObject();
el.fireEvent("on" + ename, evt);
}
return el;
},
__e_handlers: {},
//fun不能传递参数
on: document.addEventListener ? function (el, name, fun) {
if (!el) return;
if (el.MyJs) el = el[0];
el.addEventListener(name, fun, false);
} : function (el, name, fun) {
if (!el) return;
if (el.MyJs) el = el[0];
var ns = new Date().getTime();
if (!el.__e_ns) el.__e_ns = ns;
if (!fun.__e_ns) fun.__e_ns = ns;
this.__e_handlers[el.__e_ns + '_' + fun.__e_ns] = function (e) {
e.currentTarget = el;
fun(e);
};
el.attachEvent('on' + name, this.__e_handlers[el.__e_ns + '_' + fun.__e_ns]);
},
un: document.removeEventListener ? function (el, name, fun) {
if (!el) return;
if (el.MyJs) el = el[0];
el.removeEventListener(name, fun, false);
} : function (el, name, fun) {
if (!el) return;
if (el.MyJs) el = el[0];
if (el.__e_ns && fun.__e_ns)
el.detachEvent('on' + name, this.__e_handlers[el.__e_ns + '_' + fun.__e_ns]);
},
stop: function (e) {
e.returnValue = false;
if (e.preventDefault) {
e.preventDefault();
}
MyJs.Event.stopPropagation(e);
},
//stopPropagation
stopPropagation: function (e) {
e.cancelBubble = true;
if (e.stopPropagation) {
e.stopPropagation();
}
},
//take the event target who listened event
target: function (e) {
return MyJs(e.currentTarget);
},
//take the position of the event 事件的绝对坐标{x, y}
pos: function (e) {
if (e.pageX || e.pageY) {
return {
x: e.pageX,
y: e.pageY
};
}
return {
x: e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft),
y: e.clientY + (document.documentElement.scrollTop || document.body.scrollTop)
};
},
mousePos: function () {//获取鼠标坐标
return this.pos(window.event);
}
};
/************************************************* Browser ******************************************************/
var agent = navigator.userAgent.toLowerCase();
MyJs.Browser = {
version: (agent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/) || [0, '0'])[1],
safari: /webkit/i.test(agent) && !this.chrome,
opera: /opera/i.test(agent),
firefox: /firefox/i.test(agent),
ie: /msie/i.test(agent) && !/opera/.test(agent),
chrome: /chrome/i.test(agent) && /webkit/i.test(agent) && /mozilla/i.test(agent)
};
/************************************************** url *******************************************************/
MyJs.Url = {
//js获取url参数值 para:参数名称 如没值则返回"" 去除最后#符号
getParaValue: function (para) {
var url = location.href;
if (url.indexOf("#") != -1) { url = url.substring(0, url.indexOf("#")); }
var reg = new RegExp("(^|&)" + para + "=([^&]*)(&|$)");
var r = url.substr(url.indexOf("\?") + 1).match(reg);
if (r != null) return unescape(r[2]); return "";
},
//js页面跳转 _url:网址
goToUrl: function (_url) {
window.location.href = _url;
},
//获得网站根路径的方法
getRootPath: function () {
var pathName = window.location.pathname.substring(1);
var webName = pathName == '' ? '' : pathName.substring(0, pathName.indexOf('/'));
return window.location.protocol + '//' + window.location.host + '/' + webName;
}
};
/************ 配套相关方法 **************/
var ext = function (target, src, is) {
if (!target) target = {};
for (var it in src) {
if (is) {
target[it] = MyJs.Function.bind(function () {
var c = arguments[0], f = arguments[1];
var args = [this];
for (var i = 2, il = arguments.length; i < il; i++) {
args.push(arguments[i]);
}
return c[f].apply(c, args);
}, null, src, it);
} else {
target[it] = src[it];
}
}
};
var _onlyPush = function (arr, it) {
if (it.constructor != Array) it = [it];
return MyJs.Array.unique(arr.concat(it));
};
/************ 初始化 **************/
ext(Object, MyJs.Object, false);
ext(window.Class = {}, MyJs.Class, false);
ext(String.prototype, MyJs.String, true);
ext(Function.prototype, MyJs.Function, true);
ext(Array.prototype, MyJs.Array, true);
ext(Date.prototype, MyJs.Date, true);
window.$ = MyJs;
/************ 常用方法 **************/
MyJs
最新推荐文章于 2022-08-06 21:44:26 发布