AppBaseJs 类库 网上常用的javascript函数及其他js类库写的


Posted in Javascript onMarch 04, 2010
/*----------------------------------- 
Web Application JavaScript Library 
2009.11 janchie 
------------------------------------*/ //String原生对象扩展 置空左右端空格 
String.prototype.trim = function(){ 
return this.replace(/(^[\s\n\t\r]*)|([\s\n\r\t]*$)/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); 
}, 
// 浏览器检测 
isOpera: isOpera, 
isChrome: isChrome, 
isWebKit: isWebKit, 
isSafari: isSafari, 
isIE: isIE, 
isFF: isFF, 
isQuirks:quirks, 
getVersion:version, 
//取id元素 
$: function(id) { 
return typeof id === "string" ? doc.getElementById(id) : id; 
}, 
//取name元素集合 
$N:function(name){ 
return doc.getElementsByName(name); 
}, 
//取tag元素集合 
$T:function(tag, root){ 
return (root || doc).getElementsByTagName(tag); 
}, 
//按属性名(是否包含)、值、范围取元素集合 
$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; 
}, 
//取body元素 
$B: doc.body || docelem, 
//取Class属性元素集合 
$C:function(attrValue, tag, root){ 
return this.$A("className",attrValue, tag, root); 
}, 
//取浏览器窗体宽度 
getWinWidth: win.innerWidth || docelem.clientWidth || doc.body.clientWidth, 
//取浏览器窗体高度 
getWinHeight: win.innerHeight || docelem.clientHeight || doc.body.clientHeight, 
//取元素样式 
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; 
} 
}, 
//获取元素屏幕坐标值 
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}; 
}; 
}(), 
//设置透明度 
setOpacity: function (elem,num){ 
if(elem.filters){ 
elem.style.filter = "alpha(opacity="+num+")"; 
}else{ 
elem.style.opacity = num/100; 
} 
}, 
//隐藏或显示元素 
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"; 
}, 
//元素Class属性操作 
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,''); 
} 
}, 
//追加Html文本对象( 支持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:function(elem){ 
if (elem.parentNode) elem.parentNode.removeChild(elem); 
}, 
//置空元素内容及子节点 
empty:function(elem){ 
while(elem.firstChild){ 
elem.removeChild(elem.firstChild); 
} 
}, 
//图像预加载 
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():doc.ready(loads); 
}, 
//事件绑定 
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: 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; 
} 
}, 
//禁止事件冒泡 
stopPropagation: function(ev) { 
if (ev.stopPropagation) { 
ev.stopPropagation(); 
} else { 
ev.cancelBubble = true; 
} 
}, 
//禁止默认事件动作 
preventDefault: function(ev) { 
if (ev.preventDefault) { 
ev.preventDefault(); 
} else { 
ev.returnValue = false; 
} 
}, 
//获取鼠标位置 
getXY: function(ev){ 
return { 
x:ev.pageX ? ev.pageX : ev.clientX + docelem.scrollLeft, 
y:ev.pageY ? ev.pageY : ev.clientY + docelem.scrollTop 
}; 
}, 
//绑定拖动事件 
drag: function (obj, obj2){//obj:移动的对象 obj2:拖动点 
obj2 = obj2 || obj; //如果不设拖动点,那么拖动点即移动的对象 
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; 
} 
}, 
//绑定横向滚动事件 
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); 
} 
}, 
//绑定竖向滚动事件 
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); 
} 
}, 
//设置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=/'; 
}, 
//获取cookie 
getCookie:function(n){ 
var arr = doc.cookie.match(new RegExp("(^| )"+ n +"=([^;]*)(;|$)")); 
if(arr != null) return unescape(arr[2]); 
return null; 
} 
}); 
})(document,window); 
//日期字符串格转日期 
App.parseDate = function(date){ 
var dt = date instanceof Date ? date: Date(date.replace("-","/")); 
return isNaN(dt.getTime()) ? null : dt ; 
}; 
//Json字符串转对象 
App.parseJSON = function(jsonString) { 
var result = false; 
try { 
result = eval('(' + jsonString + ')'); 
}catch (e) {}; 
return result; 
}; 
//取不重复唯一值 
App.getUid = function(){ 
return "uid"+(new Date()).getTime()+ parseInt(Math.random()*100000); 
}; 
//获取指定范围的随机数 
App.random = function (n1, n2){ 
return Math.floor(Math.random()*(n2-n1+1)) + n1; 
}; 
//秒转换为毫秒 
App.s2ms = function (str){ 
var t = str.split(":"); 
return t[0] * 60000 + t[1] * 1000; 
}; 
//毫秒转换为秒 
App.ms2s = function (ms){ 
return (ms/60000+":"+ms/1000%60).replace(/\.\d+/g,"").replace(/(^|:)(\d)(?!\d)/g,"$10$2"); 
}; 
//数字转换为编号 
App.num2number = function (num, n){ 
return Array(n).join("0").concat(num).slice(-n); 
}; 
//数字转化为中文 
App.num2gb = function (n){ 
return "零一二三四五六七八九".split("")[n]; 
}; 
//Flash生成代码 
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+'>'; 
}; 
//播放器生成代码 
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+'>'; 
}; 
//获取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;i<l;i++){ 
try{ 
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); 
};

有少量函数未经测试,欢迎大家提个意见
Javascript 相关文章推荐
js 实现无干扰阴影效果 简单好用(附文件下载)
Dec 27 Javascript
基于Jquery的将DropDownlist的选中值赋给label的实现代码
May 06 Javascript
js实现图片旋转的三种方法
Apr 10 Javascript
jQuery 计算iframe 窗口大小的方法
May 13 Javascript
js实现百度联盟中一款不错的图片切换效果完整实例
Mar 04 Javascript
jQuery下拉美化搜索表单效果代码分享
Aug 25 Javascript
select标签设置默认选中的选项方法
Mar 02 Javascript
详解Vue webapp项目通过HBulider打包原生APP
Jun 29 Javascript
Vue起步(无cli)的啊教程详解
Apr 11 Javascript
vue组件讲解(is属性的用法)模板标签替换操作
Sep 04 Javascript
vue3为什么要用proxy替代defineProperty
Oct 19 Javascript
JS Object构造函数之Object.freeze
Apr 28 Javascript
JavaScript类和继承 constructor属性
Mar 04 #Javascript
爆炸式的JS圆形浮动菜单特效代码
Mar 03 #Javascript
js 编写规范
Mar 03 #Javascript
jquery validation插件表单验证的一个例子
Mar 03 #Javascript
Jquery 实现Tab效果 思路是js思路
Mar 02 #Javascript
JavaScript页面刷新与弹出窗口问题的解决方法
Mar 02 #Javascript
在一个浏览器里呈现所有浏览器测试结果的前端测试工具的思路
Mar 02 #Javascript
You might like
一个程序下载的管理程序(三)
2006/10/09 PHP
在JavaScript中通过URL传递汉字的方法
2007/04/09 Javascript
js给onclick赋值传参数的两种方法
2013/11/25 Javascript
$(document).ready(function() {})不执行初始化脚本
2014/06/19 Javascript
jQuery标签替换函数replaceWith()的使用例子
2014/08/28 Javascript
JavaScript极简入门教程(二):对象和函数
2014/10/25 Javascript
对比分析json及XML
2014/11/28 Javascript
JavaScript之Object类型介绍
2015/04/01 Javascript
详解JavaScript跨域总结与解决办法
2016/10/31 Javascript
angularJS深拷贝详解
2017/03/23 Javascript
使用nodeJs来安装less及编译less文件为css文件的方法
2017/11/20 NodeJs
Mint-UI时间组件起始时间问题及时间插件使用
2018/08/20 Javascript
解决vue 绑定对象内点击事件失效问题
2018/09/05 Javascript
JS实现的冒泡排序,快速排序,插入排序算法示例
2019/03/02 Javascript
[02:43]DOTA2亚洲邀请赛场馆攻略——带你走进东方体育中心
2018/03/19 DOTA
Python实现扫描指定目录下的子目录及文件的方法
2014/07/16 Python
python制作爬虫爬取京东商品评论教程
2016/12/16 Python
python中的插值 scipy-interp的实现代码
2018/07/23 Python
Django组件之cookie与session的使用方法
2019/01/10 Python
在linux下实现 python 监控usb设备信号
2019/07/03 Python
python点击鼠标获取坐标(Graphics)
2019/08/10 Python
通过Turtle库在Python中绘制一个鼠年福鼠
2020/02/03 Python
浅谈Django QuerySet对象(模型.objects)的常用方法
2020/03/28 Python
python安装sklearn模块的方法详解
2020/11/28 Python
Python爬虫实例之2021猫眼票房字体加密反爬策略(粗略版)
2021/02/22 Python
东南亚旅游平台:The Trip Guru
2018/01/01 全球购物
C语言怎样定义和声明全局变量和函数最好
2013/11/26 面试题
main 函数执行以前,还会执行什么代码
2013/04/17 面试题
客户代表自我评价范例
2013/09/24 职场文书
“四风”问题自我剖析材料思想汇报
2014/09/23 职场文书
离婚协议书范本(通用篇)
2014/11/30 职场文书
投资合作意向书范本
2015/05/08 职场文书
关于观后感的作文
2015/06/18 职场文书
小学大队长竞选稿
2015/11/20 职场文书
一劳永逸彻底解决pip install慢的办法
2021/05/24 Python
为什么MySQL选择Repeatable Read作为默认隔离级别
2021/07/26 MySQL