Home Web Front-end JS Tutorial AppBaseJs class library commonly used javascript functions on the Internet and other js class libraries written_js object-oriented

AppBaseJs class library commonly used javascript functions on the Internet and other js class libraries written_js object-oriented

May 16, 2016 pm 06:33 PM
javascript function Class library

Copy code The code is as follows:

/*-----------------------------------
Web Application JavaScript Library
2009.11 janchie
------------------------------------*/

//String原生对象扩展 置空左右端空格
String.prototype.trim = function(){
return this.replace(/(^[sntr]*)|([snrt]*$)/g, "");
};
//Date原生对象扩展 格式化输出
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() < 13 ? 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();
};
/*------------------------------------*/

//声明对象
var App = {};
//对象继承或属性合并
App.extend = function(obj, hash) {
this.each(hash, function(key, value) {
obj[key] = value;
});
return obj;
};
//遍历
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(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加载
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,{
//类型检测
isArray: function(v) { //是否为数组
return string.apply(v) === "[object Array]";
},
isFunction: function(v) { //是否为函数体
return string.apply(v) === "[object Function]";
},
isNumber: function(v) { //是否为数字
return typeof v === "number" && isFinite(v);
},
isDate: function(v) { //是否为日期
return string.apply(v) === "[object Date]";
},
isElement: function(v) { //是否为Dom元素节点
return !!(v && v.nodeType === 1);
},
// Browser detection
isOpera: isOpera,
isChrome: isChrome,
isWebKit: isWebKit,
isSafari: isSafari,
isIE: isIE,
isFF: isFF ,
isQuirks:quirks,
getVersion:version,

//Get the id element
$: function(id) {
return typeof id === "string" ? doc .getElementById(id) : id;
},
//Get the name element collection
$N:function(name){
return doc.getElementsByName(name);
},
//Get the tag element collection
$T:function(tag, root){
return (root || doc).getElementsByTagName(tag);
},
//By attribute name (Whether it contains), value, and range take the set of elements
$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; iattr = 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;
},
//Get the body element
$B: doc.body | | docelem,
//Get the collection of Class attribute elements
$C:function(attrValue, tag, root){
return this.$A("className",attrValue, tag, root);
},
//Get the browser window width
getWinWidth: win.innerWidth || docelem.clientWidth || doc.body.clientWidth,
//Get the browser window height
getWinHeight : win.innerHeight || docelem.clientHeight || doc.body.clientHeight,
//Get the 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 the 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 operation
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 (supports 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);
},
//Remove 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 preloading
loadimages: function(){
var a = arguments ,loads = function(){
if(doc.images){ if(!doc.ps) doc.ps = [];
var i,j=doc.ps.length; for(i=0 ; iif (a[i].indexOf("#")!=0){ doc.ps[j] = new Image; doc.ps[j ].src=a [i];}}
};
arguments.callee.caller ? loads():doc.ready(loads);
},

//Event binding
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(){};
}
}(),
//Unbind event
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;
}
},
//Disable event bubbling
stopPropagation: function(ev) {
if (ev.stopPropagation) {
ev.stopPropagation();
} else {
ev.cancelBubble = true;
}
},
//Prohibit default event action
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
};
},
//Bind drag event
drag: function (obj, obj2){//obj: moving object obj2: drag point
obj2 = obj2 || obj; //If there is no drag point, then the drag point is the moving object
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;
}
},
//Bind horizontal scrolling event
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(xif(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);
}
},
//Bind vertical scroll event
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(yif(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 cookie
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() ';path=/';
},
//Get cookie
getCookie:function(n){
var arr = doc.cookie.match(new RegExp("(^| )" n "=([^;]*)(;|$)"));
if(arr != null) return unescape (arr[2]);
return null;
}
});
})(document,window);

//date string format to date
App.parseDate = function(date){
var dt = date instanceof Date ? date: Date(date.replace("-","/"));
return isNaN(dt.getTime()) ? null : dt ;
};
//Json string to object
App.parseJSON = function(jsonString) {
var result = false;
try {
result = eval('(' jsonString ')');
}catch (e) {};
return result;
};
//Get a non-repeating unique value
App.getUid = function(){
return "uid" (new Date()).getTime() parseInt(Math.random()*100000);
};
//Get a random number in the specified range
App.random = function (n1, n2){
return Math.floor(Math.random()*(n2-n1 1)) n1;
};
//Convert seconds to milliseconds
App.s2ms = function (str){
var t = str.split(":");
return t[0] * 60000 t[1] * 1000;
};
//Convert milliseconds to seconds
App.ms2s = function (ms){
return (ms/60000 ":" ms/1000`).replace(/.d /g,"").replace( /(^|:)(d)(?!d)/g,"$10$2");
};
//Convert numbers to numbers
App.num2number = function (num, n) {
return Array(n).join("0").concat(num).slice(-n);
};
//Convert numbers to Chinese
App.num2gb = function (n){
return "zero one two three four five six seven eight nine".split("")[n];
};
//Flash generation 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('');
return '<' tagName a1.join(' ') '>' a2.join('') '';
};
//播放器生成代码
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('');
return '<' tagName a1.join(' ') '>' a2.join('') '';
};
//获取XMLHttp对象
App.xmlhttp = function (){
if (this.isFF) return 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;itry{
return new ActiveXObject(a[i]);
}catch(e){}
}
return false;
};
//Get数据
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数据
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);
};

有少量函数未经测试,欢迎大家提个意见
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Asynchronous Programming of JavaScript Functions: Essential Tips for Handling Complex Tasks Asynchronous Programming of JavaScript Functions: Essential Tips for Handling Complex Tasks Nov 18, 2023 am 10:06 AM

JavaScript Function Asynchronous Programming: Essential Skills for Handling Complex Tasks Introduction: In modern front-end development, handling complex tasks has become an indispensable part. JavaScript function asynchronous programming skills are the key to solving these complex tasks. This article will introduce the basic concepts and common practical methods of JavaScript function asynchronous programming, and provide specific code examples to help readers better understand and use these techniques. 1. Basic concepts of asynchronous programming In traditional synchronous programming, the code is

Use JavaScript functions to implement web page navigation and routing Use JavaScript functions to implement web page navigation and routing Nov 04, 2023 am 09:46 AM

In modern web applications, implementing web page navigation and routing is a very important part. Using JavaScript functions to implement this function can make our web applications more flexible, scalable and user-friendly. This article will introduce how to use JavaScript functions to implement web page navigation and routing, and provide specific code examples. Implementing web page navigation For a web application, web page navigation is the most frequently operated part by users. When a user clicks on the page

Real-time updates to data visualizations using JavaScript functions Real-time updates to data visualizations using JavaScript functions Nov 04, 2023 pm 03:30 PM

Real-time updates of data visualization using JavaScript functions With the development of data science and artificial intelligence, data visualization has become an important data analysis and display tool. By visualizing data, we can understand the relationships and trends between data more intuitively. In web development, JavaScript is a commonly used scripting language with powerful data processing and dynamic interaction functions. This article will introduce how to use JavaScript functions to achieve real-time updates of data visualization, and show the specific

Use JavaScript functions to implement image carousels and slideshow effects Use JavaScript functions to implement image carousels and slideshow effects Nov 04, 2023 am 08:59 AM

JavaScript is a scripting language that can be used to add interactive effects to web pages. Among them, image carousel and slideshow effects are common web page animation effects. This article will introduce how to use JavaScript functions to achieve these two effects and provide specific code examples. Picture carousel Picture carousel is an effect that plays multiple pictures in turn in a certain way. When implementing image carousels, JavaScript timers and CSS style controls need to be used. (1) Preparation work First, in the HTML file

Use JavaScript functions to implement user login and permission verification Use JavaScript functions to implement user login and permission verification Nov 04, 2023 am 10:10 AM

Using JavaScript functions to implement user login and permission verification With the development of the Internet, user login and permission verification have become essential functions for many websites and applications. In order to protect users' data security and access rights, we need to use some technologies and methods to verify the user's identity and restrict their access rights. As a widely used scripting language, JavaScript plays an important role in front-end development. We can use JavaScript functions to implement user login and permission verification functions

Know all about Go language libraries: important libraries you can't miss Know all about Go language libraries: important libraries you can't miss Mar 02, 2024 am 08:15 AM

For Go language developers, choosing the right class library is crucial. Excellent class libraries can greatly improve development efficiency and avoid reinventing the wheel. In the Go language world, there are many excellent class libraries for us to choose from, but there are also some "must-have" class libraries. Today I will introduce to you some important class libraries that I think should not be missed in actual projects, and provide specific Code examples are provided for your reference. Whether GorillaMux is building a RESTful API or a web application, routing is an indispensable part.

Use JavaScript functions to achieve user interaction and dynamic effects Use JavaScript functions to achieve user interaction and dynamic effects Nov 03, 2023 pm 07:02 PM

Using JavaScript functions to achieve user interaction and dynamic effects With the development of modern web design, user interaction and dynamic effects have become the key to attracting users' attention. As a commonly used scripting language, JavaScript has powerful functions and flexible features, and can achieve a variety of user interactions and dynamic effects. This article will introduce some common JavaScript functions and give specific code examples. Changing element style (style) can be easily changed through JavaScript functions

Use JavaScript functions to upload and download files Use JavaScript functions to upload and download files Nov 04, 2023 am 08:30 AM

Using JavaScript functions to implement file upload and download With the development and popularization of the Internet, file upload and download have become one of the common functions in web applications. This article will introduce how to use JavaScript functions to implement file upload and download functions, and provide specific code examples. File upload File upload refers to uploading local files to the server through a web page. FileAPI is provided in HTML5 to handle the selection and upload of files. We can take advantage of Fi in FileAPI

See all articles