Appbasejs class Library On-line common JavaScript functions and other JS class library write _js object-oriented

Source: Internet
Author: User
Tags getdate tagname
Copy Code code as follows:

/*-----------------------------------
WEB Application JavaScript Library
2009.11 Janchie
------------------------------------*/

String native object extension empty left and right space
String.prototype.trim = function () {
Return This.replace (/(^[\s\n\t\r]*) | ( [\s\n\r\t]*$)/g, "");
};
Date native object Extended formatted output
Date.prototype.format = function (string) {
var self = this;
var p = function p (s) {
Return (s.tostring (). length = = 1)? "0" + s:s;
};
return string? String.Replace (/dd?d?d?| Mm? M? m?| yy?y?y?| hh?| hh?| mm?| ss?| tt?| Zz?z?/g,
function (String) {
Switch (string) {
Case "HH": Return P (self.gethours () < Self.gethours (): (Self.gethours ()-12));
Case "H": Return Self.gethours () < 13? Self.gethours (): (Self.gethours ()-12);
Case "HH": Return P (self.gethours ());
Case "H": Return Self.gethours ();
Case "MM": Return P (Self.getminutes ());
Case "M": Return Self.getminutes ();
Case "SS": Return P (Self.getseconds ());
Case "S": Return Self.getseconds ();
Case "yyyy": return Self.getfullyear ();
Case "yy": Return Self.getfullyear (). toString (). SUBSTRING (2, 4);
Case "dddd": Return Self.getdayname ();
Case "DDD": Return Self.getdayname (TRUE);
Case "DD": Return P (Self.getdate ());
Case "D": Return Self.getdate (). toString ();
Case "MMMM": Return Self.getmonthname ();
Case "MMM": Return Self.getmonthname (TRUE);
Case "MM": Return P ((Self.getmonth () + 1));
Case "M": Return Self.getmonth () + 1;
Case "T": Return Self.gethours () < 12? Date.CultureInfo.amDesignator.substring (0, 1): Date.CultureInfo.pmDesignator.substring (0, 1);
Case "TT": Return Self.gethours () < 12? Date.CultureInfo.amDesignator:Date.CultureInfo.pmDesignator;
Case "ZZZ":
Case "ZZ":
Case "Z": Return "";
}
}): This.tostring ();
};
/*------------------------------------*/

declaring objects
var App = {};
Object inheritance or Property merge
App.extend = function (obj, hash) {
This.each (hash, function (key, value) {
Obj[key] = value;
});
return obj;
};
Traverse
App.each = function (obj, func, context) {
var length = obj.length, i =-1;
if (length!== undefined) {
while (++i < length) if (Func.call (context, obj[i], I, obj, length) = = false) break;
}
else for the (var key in obj) if (Obj.hasownproperty (key)) if (Func.call (context, key, Obj[key], obj) = false) break;
return obj;
};
(Function (doc, win) {
var string = Object.prototype.toString,
Quirks = Doc.compatmode = = "Backcompat",
Docelem = Doc.documentelement,
UA = Win.navigator.userAgent.toLowerCase (),
Version = (Ua.match (/.: Rv|it|ra|ie) [\/:] ([\d.] +)/ ) || []) [1],
Ischrome =/chrome/.test (UA),
Iswebkit =/webkit/.test (UA),
Issafari =!ischrome && Iswebkit,
Isopera =/opera/.test (UA),
Isie =/msie/.test (UA) &&!isopera,
ISFF =/firefox/.test (UA);
Dom Load
Doc.ready = function (func) {
var isready = False,doready = function () {
if (IsReady) return;
IsReady = true; Func ();
};
if (Isie) {
if (docelem.doscroll && win.self = = win.top) {
(function () {
if (IsReady) return;
try {
Docelem.doscroll ("left");
catch (Error) {
settimeout (Arguments.callee, 0);
Return
}
Doready ();
})();
}else {
if (IsReady) return;
This.attachevent ("onReadyStateChange", function () {
if (doc.readystate = = "complete") {
Doc.detachevent ("onReadyStateChange", Arguments.callee);
Doready ();
}
});
}
Win.attachevent (' onload ', doready);
}else if (iswebkit && version < 525) {
(function () {
if (IsReady) return;
if (/loaded|complete/.test (doc.readystate))
Doready ();
Else
settimeout (Arguments.callee, 0);
})();
Win.addeventlistener (' Load ', Doready, false);
}else {
if (!ISFF)
This.addeventlistener ("domcontentloaded", function () {
Doc.removeeventlistener ("domcontentloaded", Arguments.callee, false);
Doready ();
}, False);
This.addeventlistener (' Load ', Doready, false);
}
};
App.extend (app,{
Type detection
Isarray:function (v) {//is an array
return string.apply (v) = = "[Object Array]";
},
Isfunction:function (v) {//is a function body
return string.apply (v) = = "[Object Function]";
},
Isnumber:function (v) {//is a number
return typeof v = = "number" && isfinite (v);
},
Isdate:function (v) {//Is the date
return string.apply (v) = = "[Object Date]";
},
Iselement:function (v) {//is a DOM element node
Return!! (v && v.nodetype = 1);
},
Browser detection
Isopera:isopera,
Ischrome:ischrome,
Iswebkit:iswebkit,
Issafari:issafari,
Isie:isie,
ISFF:ISFF,
Isquirks:quirks,
Getversion:version,

Take ID Element
$: function (ID) {
return typeof id = = "string"? Doc.getelementbyid (ID): ID;
},
Take the name element collection
$N: function (name) {
return Doc.getelementsbyname (name);
},
Take the Tag element collection
$T: function (tag, root) {
return (Root | | doc). getElementsByTagName (tag);
},
Collection of elements by property name (whether it contains), value, range
$A: Function (attrname, attrValue, tag, root) {
var elems = Doc.all? Doc.all:this. $T (Tag | | "*", root | | DOC), result = [],
AttVal = (typeof attrValue!= "undefined")? New RegExp ("(^|\\s)" + AttrValue + "(\\s|$)"): null;
for (var i=0; i<elems.length; i++) {
attr = Elems[i][attrname] | | Elems[i].getattribute (Attrname);
if (typeof attr = = "string" && attr.length > 0) {
if (typeof AttrValue = = "Undefined" | | (AttVal && attval.test (attr)) {
Result.push (Elems[i]);
}
}
}
return result;
},
Take the BODY element
$B: Doc.body | | Docelem,
Fetch CLASS Attribute element collection
$C: function (AttrValue, tag, root) {
return this. $A ("ClassName", AttrValue, tag, root);
},
Take browser form width
GetWinWidth:win.innerWidth | | Docelem.clientwidth | | Doc.body.clientWidth,
Take the browser form height
GetWinHeight:win.innerHeight | | Docelem.clientheight | | Doc.body.clientHeight,
Take element style
Getstyle:function (elem,name) {
if (Elem.style[name]) {
return Elem.style[name];
}else if (elem.currentstyle) {
return Elem.currentstyle[name];
}else if (Doc.defaultview && doc.defaultView.getComputedStyle) {
name = Name.replace ([[A-z])/g, "-$1");
Name = Name.tolowercase ();
var s = doc.defaultView.getComputedStyle (Elem, "");
return s && s.getpropertyvalue (name);
}else{
return null;
}
},
Get element Screen coordinate value
Getposition:function () {
Return docelem.getboundingclientrect && function (o) {
var pos = O.getboundingclientrect (), root = O.ownerdocument | | O.doc;
return {left:pos.left+root.documentelement.scrollleft,top:pos.top+root.documentelement.scrolltop};
} || Function (o) {
var x = 0, y = 0;
Do{x + + o.offsetleft;y + = O.offsettop;} while ((o=o.offsetparent));
return {left:x,top:y};
};
}(),
Set transparency
Setopacity:function (elem,num) {
if (elem.filters) {
Elem.style.filter = "Alpha (opacity=" +num+ ")";
}else{
elem.style.opacity = num/100;
}
},
Hide or show elements
Hide:function (elem) {elem.style.display = "none";},
Show:function (elem) {elem.style.display = "block";},
Toggle:function (elem) {
Elem.style.display = This.getstyle (Elem, "display") = = "None"? Block ": none";
},
Element Class attribute action
Addclass:function (Elem, Clsname) {
if (Elem.classname = = "") {
Elem.classname = Clsname;
}else if (elem.classname!== ' && (' + Elem.classname + '). IndexOf (' + clsname + ') = = 1) {
Elem.classname = elem.classname + ' + clsname;
}
},
Removeclass:function (Elem, Clsname) {
if (Clsname && (' + Elem.classname + '). IndexOf (' + clsname + ') >-1) {
Elem.classname = (' + elem.classname + '). Replace (' + clsname + ', '). Replace (/^ | $/g, ");
}
},
Append HTML text object (support table)
Append:function (Elem, text) {
if (typeof text = = "string") {
if (elem.insertadjacenthtml) {
if (Elem.tagname = = "TABLE") {
var html = Elem.outerhtml,ep = ELEM.PARENTNODE,SL = Html.length;
Text = Html.substr (0,sl-8) + text + html.substr (SL-8,SL);
Ep.insertadjacenthtml ("BeforeEnd", text);
Ep.replacechild (Ep.lastchild,elem);
}else{
Elem.insertadjacenthtml ("BeforeEnd", text);
}
}else {
var RLT = null, RG = Doc.createrange (), FM = rg.createcontextualfragment (text);
RLT? ELEM.INSERTBEFORE (FM, RLT): ELEM.APPENDCHILD (FM);
}
}else if (typeof text = = "Object") elem.appendchild (text);
},
Delete Element
Remove:function (elem) {
if (Elem.parentnode) elem.parentNode.removeChild (elem);
},
Empty element content and child nodes
Empty:function (elem) {
while (Elem.firstchild) {
Elem.removechild (Elem.firstchild);
}
},
Image Pre-loading
Loadimages:function () {
var a = Arguments,loads = function () {
if (doc.images) {if (!doc.ps) doc.ps = [];
var i,j=doc.ps.length; for (i=0; i<a.length; i++)
if (A[i].indexof ("#")!=0) {Doc.ps[j] = new Image; doc.ps[j++].src=a[i];}
};
Arguments.callee.caller? Loads ():d oc.ready (loads);
},

Event Bindings
Bind:function () {
if (Win.addeventlistener) {
return function (Elem, stype, FNC) {
Elem.addeventlistener (Stype, FNC, false);
};
else if (win.attachevent) {
return function (Elem, stype, FNC) {
Elem.attachevent ("on" + Stype, FNC);
};
} else {
return function () {};
}
}(),
Disassociate event Bindings
Unbind:function (Elem, Stype, FNC) {
if (Elem.removeeventlistener) {
Elem.removeeventlistener (Stype, FNC, false);
}else if (elem.detachevent) {
Elem.detachevent ("on" + Stype, FNC);
}else{
Elem["on" + stype] = null;
}
},
Prevent event bubbling
Stoppropagation:function (EV) {
if (ev.stoppropagation) {
Ev.stoppropagation ();
} else {
Ev.cancelbubble = true;
}
},
Prevent default event actions
Preventdefault:function (EV) {
if (Ev.preventdefault) {
Ev.preventdefault ();
} else {
Ev.returnvalue = false;
}
},
Get mouse position
Getxy:function (EV) {
return {
X:ev.pagex? Ev.pageX:ev.clientX + Docelem.scrollleft,
Y:ev.pagey? Ev.pageY:ev.clientY + docelem.scrolltop
};
},
Binding Drag Events
Drag:function (obj, obj2) {//obj: Moved object obj2: dragging point
Obj2 = Obj2 | | Obj If you do not set a drag point, the object that is moved by the drag point
var x, y, UT = this;
Obj2.onmousedown = function (e) {
E = e | | Win.event;
Ut.preventdefault (e);
Obj.setcapture && obj.setcapture ();
x = Ut.getxy (E). X-parseint (Obj.style.left);
y = Ut.getxy (E). Y-parseint (Obj.style.top);
Docelem.onmousemove = over;
Docelem.onmouseup = up;
}
function over (e) {
E = e | | Win.event;
Obj.style.left = Ut.getxy (e). X-x + "px";
Obj.style.top = Ut.getxy (e). y-y + "px";
}
function up () {
Obj.releasecapture && obj.releasecapture ();
Docelem.onmousemove = null;
Docelem.onmouseup = null;
}
},
Binding Horizontal scrolling Events
Sliderx:function (obj,x1,x2,overevent,upevent) {
var x, T, UT = this;
Obj.onmousedown = function (e) {
E = e | | Win.event;
Ut.preventdefault (e);
Obj.setcapture && obj.setcapture ();
t = Ut.getxy (E). X-parseint (Obj.style.left);
Docelem.onmousemove = over;
Docelem.onmouseup = up;
}
function over (e) {
E = e | | Win.event;
x = Ut.getxy (e). x-t;
if (x<x1) x=x1;
if (x>x2) x=x2;
Obj.style.left = x + "px";
Overevent && overevent (x);
}
function up () {
Obj.releasecapture && obj.releasecapture ();
Docelem.onmousemove = null;
Docelem.onmouseup = null;
Upevent && upevent (x);
}
},
Binding Vertical scrolling Events
Slidery:function (obj,y1,y2,overevent,upevent) {
var y, t, UT = this;
Obj.onmousedown = function (e) {
E = e | | Win.event;
Ut.preventdefault (e);
Obj.setcapture && obj.setcapture ();
t = Ut.getxy (E). Y-parseint (Obj.style.top);
Docelem.onmousemove = over;
Docelem.onmouseup = up;
}
function over (e) {
E = e | | Win.event;
y = Ut.getxy (e). y-t;
if (y<y1) y=y1;
if (y>y2) y=y2;
Obj.style.top = y + "px";
Overevent && overevent (y);
}
function up () {
Obj.releasecapture && obj.releasecapture ();
Docelem.onmousemove = null;
Docelem.onmouseup = null;
Upevent && upevent (y);
}
},
Set cookies
Setcookie:function (n, V, t) {
var exp = new Date ();
Exp.settime (Exp.gettime () + (t| | 24) *60*60*1000);
Doc.cookie = n + "=" + Escape (v) + "expires=" + exp.togmtstring () + ';p ath=/';
},
Get cookies
Getcookie:function (n) {
var arr = Doc.cookie.match (New RegExp ("(^|)" + n + "= ([^;] *)(;|$)"));
if (arr!= null) return unescape (arr[2));
return null;
}
});
}) (Document,window);

Date string grid Turn date
App.parsedate = function (date) {
var dt = Date instanceof date? Date:date (Date.replace ("-", "/"));
Return isNaN (Dt.gettime ())? NULL:DT;
};
JSON string Spin Object
App.parsejson = function (jsonstring) {
var result = false;
try {
result = eval (' (' + jsonstring + ') ');
}catch (e) {};
return result;
};
Take no duplicate unique value
App.getuid = function () {
Return "UID" + (new Date ()). GetTime () + parseint (Math.random () *100000);
};
Gets the random number of the specified range
App.random = function (n1, N2) {
Return Math.floor (Math.random () * (n2-n1+1)) + N1;
};
Seconds to milliseconds
app.s2ms = function (str) {
var t = str.split (":");
return T[0] * 60000 + t[1] * 1000;
};
Milliseconds conversion to seconds
App.ms2s = function (ms) {
Return (ms/60000+ ":" +ms/1000%60). Replace (/\.\d+/g, ""). Replace (/(^|:) (\d) (?! \d)/g, "$10$2");
};
Number converted to number
App.num2number = function (num, n) {
return Array (n). Join ("0"). Concat (num). Slice (-N);
};
Convert numbers to Chinese
APP.NUM2GB = function (n) {
Return "0123456789". Split ("") [n];
};
Flash Generate code
App.getflash = function (url, width, height, param) {
var tagName = "", O1 = {width:width| | 1, height:height| | 1}, O2 = {};
if (This.isie) {
TagName = "Object";
O1.classid = "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000";
O1.codebase = "http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=10,0,0,0";
O2.movie = URL;
O2.quality = "High";
Param && this.extend (O2, param);
}else{
TagName = "Embed";
O1.type = "Application/x-shockwave-flash";
O1.pluginspage = "HTTP://WWW.ADOBE.COM/GO/GETFLASHPLAYER_CN";
o1.src = URL;
O1.quality = "High";
Param && this.extend (O1, param);
}
if (o1.width<2&&o1.height<2) tagname+= ' style= ' position:absolute; top:-100px; " ';
var a1=[], a2=[], I;
For (i in O1) a1.push (i+ ' = "' +o1[i]+ '");
For (i in O2) A2.push (' <param name= ' +i+ ' value= ' "+o2[i]+ '");
Return ' < ' +tagname+a1.join (') + ' > ' +a2.join (') + ' </' +tagname+ ' > ';
};
Player Generation Code
App.getplayer = function (url, width, height, param) {
var wmp = ["6bf52a52-394a-11d3-b153-00c04f79faa6", "Application/x-mplayer2"];
var RMP = ["CFCDAA03-8BE4-11CF-B84B-0020AFBBCCFA", "Audio/x-pn-realaudio-plugin"];
var MP =/\.rm$/.test (URL)? RMP:WMP;
var tagName = "", O1 = {width:width| | 1, height:height| | 1}, O2 = {};
if (This.isie) {
TagName = "Object";
O1.classid = "clsid:" +mp[0];
O2.url = URL;
Param && this.extend (O2, param);
}else{
TagName = "Embed";
O1.type = mp[1];
o1.src = URL;
Param && this.extend (O1, param);
}
if (o1.width<2&&o1.height<2) tagname+= ' style= ' position:absolute; top:-100px; " ';
var a1=[], a2=[], I;
For (i in O1) a1.push (i+ ' = "' +o1[i]+ '");
For (i in O2) A2.push (' <param name= ' +i+ ' value= ' "+o2[i]+ '");
Return ' < ' +tagname+a1.join (') + ' > ' +a2.join (') + ' </' +tagname+ ' > ';
};
Get XMLHTTP Object
App.xmlhttp = function () {
if (THIS.ISFF) return the new XMLHttpRequest ();
var a = ["msxml2.xmlhttp.3.0", "Msxml2.xmlhttp", "Microsoft.XMLHTTP", "msxml2.xmlhttp.4.0", "msxml2.xmlhttp.5.0"];
for (Var i=0,l=a.length;i<l;i++) {
try{
return new ActiveXObject (A[i]);
}catch (e) {}
}
return false;
};
Get Data
App.get = function (url,callback) {
var x = This.xmlhttp ();
X.open ("Get", url,true);
X.onreadystatechange = function () {
X.readystate==4 && (x.status==0| | x.status==200) && callBack (X.responsetext);
}
X.send (NULL);
};
Post data
App.post = function (url,arg,callback) {
var x = This.xmlhttp ();
X.open ("Post", url,true);
X.setrequestheader ("Content-length", arg.length);
X.setrequestheader ("Content-type", "application/x-www-form-urlencoded");
X.onreadystatechange = function () {
X.readystate==4 && (x.status==0| | x.status==200) && callBack (X.responsetext);
}
X.send (ARG);
};

There are a few functions that have not been tested and you are welcome to comment
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.