Date工具類
/********************** date工具類 ***************/
Date.prototype.format = function(format){
var o = {
"M+" : this.getMonth()+1, //month
"d+" : this.getDate(), //day
"h+" : this.getHours(), //hour
"m+" : this.getMinutes(), //minute
"s+" : this.getSeconds(), //second
"q+" : Math.floor((this.getMonth()+3)/3), //quarter
"S" : this.getMilliseconds() //millisecond
}
if(/(y+)/.test(format)) format=format.replace(RegExp.$1,(this.getFullYear()+"").substr(4- RegExp.$1.length));
for(var k in o)if(new RegExp("("+ k +")").test(format))
format = format.replace(RegExp.$1,RegExp.$1.length==1? o[k] : ("00"+ o[k]).substr((""+ o[k]).length));
return format;
};
公共工具類
對(duì)輸入框里內(nèi)容清空,對(duì)textarea,可以直接$("textarea").empty();如果使用$("textarea").html("");也可能會(huì)造成瀏覽器內(nèi)存溢出。
/********************** 公共工具類 ***************/
var PublicUtil ={
isNotEmpty: function(val){
return !this.isEmpty(val);
},
isEmpty: function(val){
if ((val==null || typeof(val)=="undefined")|| (typeof(val)=="string"&&val==""&&val!="undefined")){
return true;
}else{
return false;
}
},
isDebug: function(){
if(this.isNotEmpty(configDebug)&&configDebug=="true"){
return true;
}else{
return false;
}
},
//去除元素內(nèi)所有內(nèi)容 strIds:"#id1,#id2,#id3"
emptyHtml: function(strIds){
try{
var ids = strIds.trim(",").split(",");
$(ids).each(function(){
var obj = $(this.toString());
if(obj.length>0){
$(obj).each(function(){
$(this).html("");
});
}else{
obj.html("");
}
});
}catch(ex){
if(PublicUtil.isDebug()){
throw new Error("js方法:【PublicUtil.emptyHtml(strIds)】,error!");
}
}
},
//去除元素的值 strIds:"#id1,#id2,#id3"
emptyValue: function(strIds){
try{
var ids = strIds.trim(",").split(",");
$(ids).each(function(){
var obj = $(this.toString());
if(obj.length>0){
$(obj).each(function(){
$(this).val("");
});
}else{
obj.val("");
}
});
}catch(ex){
if(PublicUtil.isDebug()){
throw new Error("js方法:【PublicUtil.emptyValue(strIds)】,error!");
}
}
},
//去除Textarea內(nèi)所有內(nèi)容 strIds:"#id1,#id2,#id3"
emptyTextarea: function(strIds){
try{
var ids = strIds.trim(",").split(",");
$(ids).each(function(){
var obj = $(this.toString());
if(obj.length>0){
$(obj).each(function(){
$(this).empty();
$(this).val("");
});
}else{
obj.empty();
obj.val("");
}
});
}catch(ex){
if(PublicUtil.isDebug()){
throw new Error("js方法:【PublicUtil.emptyTextarea(strIds)】,error!");
}
}
}
}
String工具類
字符串的拼接一定使用StringBuffer來(lái)拼接,否則容易造成瀏覽器卡頓或內(nèi)存溢出。特別是針對(duì)一些執(zhí)行js效率不高的瀏覽器!!
/********************** String工具類***************/
//trim去掉字符串兩邊的指定字符,默去空格
String.prototype.trim = function(tag) {
if (!tag) {
tag = '\\s';
}else {
if (tag == '\\') {
tag = '\\\\';
} else if (tag == ',' || tag == '|' || tag == ';') {
tag = '\\' + tag;
}else {
tag = '\\s';
}
}
eval('var reg=/(^' + tag + '+)|(' + tag + '+$)/g;');
return this.replace(reg, '');
};
//字符串截取后面加入...
String.prototype.interceptString = function(len) {
if (this.length > len) {
return this.substring(0, len) + "...";
} else {
return this;
}
}
//將一個(gè)字符串用給定的字符變成數(shù)組
String.prototype.toArray = function(tag) {
if (this.indexOf(tag) != -1) {
return this.split(tag);
}else {
if (this != '') {
return [this.toString()];
}else {
return [];
}
}
}
//只留下數(shù)字(0123456789)
String.prototype.toNumber= function() {
return this.replace(/\D/g, "");
}
//保留中文
String.prototype.toCN= function() {
var regEx = /[^\u4e00-\u9fa5\uf900-\ufa2d]/g;
return this.replace(regEx, '');
}
//轉(zhuǎn)成int
String.prototype.toInt= function() {
var temp = this.replace(/\D/g, "");
return isNaN(parseInt(temp)) ? this.toString() : parseInt(temp);
}
//是否是以XX開(kāi)頭
String.prototype.startsWith= function(tag){
return this.substring(0, tag.length) == tag;
}
//是否已XX結(jié)尾
String.prototype.endWith= function(tag){
return this.substring(this.length - tag.length) == tag;
}
//StringBuffer
var StringBuffer = function() {
this._strs = new Array;
};
StringBuffer.prototype.append = function (str) {
this._strs.push(str);
};
StringBuffer.prototype.toString = function() {
return this._strs.join("");
};
String.prototype.replaceAll = function(s1,s2){
return this.replace(new RegExp(s1,"gm"),s2);
}
Array工具類
/********************** Arry ***************/
//根據(jù)數(shù)據(jù)取得再數(shù)組中的索引
Array.prototype.getIndex = function(obj){
for (var i = 0; i < this.length; i++) {
if (obj == this[i]) {
return i;
}
}
return -1;
}
//移除數(shù)組中的某元素
Array.prototype.remove= function (obj) {
for (var i = 0; i < this.length; i++) {
if (obj == this[i]) {
this.splice(i, 1);
break;
}
}
return this;
}
//判斷元素是否在數(shù)組中
Array.prototype.contains= function (obj) {
for (var i = 0; i < this.length; i++) {
if (obj == this[i]) {
return true;
}
}
return false;
}
瀏覽器相關(guān)操作
/********************** 瀏覽器相關(guān)操作 ***************/
//進(jìn)入全屏模式, 判斷各種瀏覽器,找到正確的方法
var launchFullScreen = function (element) {
if(element.requestFullscreen) {
element.requestFullscreen();
} else if(element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if(element.webkitRequestFullscreen) {
element.webkitRequestFullscreen();
} else if(element.msRequestFullscreen) {
element.msRequestFullscreen();
}
return true;
}
//退出全屏模式
var exitFullScreen = function () {
if(document.exitFullscreen) {
document.exitFullscreen();
} else if(document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if(document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
return false;
}
//cookie操作
var CookieUtil={
path: "/",
domain: 'demo.j2ee.com',
add: function(name,val){
$.cookie(name, val, {expires: 7, path: this.path, domain: this.domain, secure: true});
},
remove: function(name){
$.cookie(name, null,{path: this.path, domain: this.domain});
},
get: function(name){
$.cookie(name,{path: this.path, domain: this.domain});
}
}
//error
var error={
e_404: function(){
alertMessage("404","未找到改頁(yè)面!","warning");
},
e_500: function(){
alertMessage("500","服務(wù)器內(nèi)部錯(cuò)誤!","error");
},
e_403: function(){
alertMessage("403","權(quán)限不足!","warning");
}
}
層拖動(dòng)對(duì)象類
原理:
需拖動(dòng)的層包括兩類對(duì)象,主移動(dòng)區(qū)域,鼠標(biāo)拖動(dòng)事件區(qū)域(可與主移動(dòng)區(qū)域一致),鼠標(biāo)在事件區(qū)域按下時(shí)為其注冊(cè)鼠標(biāo)移動(dòng)及鼠標(biāo)釋放事件,非IE瀏覽器需為document注冊(cè)事件,同時(shí)為其設(shè)置捕獲事件(關(guān)鍵事件setCapture),鼠標(biāo)移動(dòng)時(shí)重置主區(qū)域Style中的位置屬性(left,top),釋放鼠標(biāo)后移除事件綁定。
$.extend({
ObjMove: function (op) {
var settings = $.extend({
containerId: 'divPopWindow', //容器編號(hào)
dragIds: ['divPopWindowDragTop', 'divPopWindowDragBottom'], //拖動(dòng)層編號(hào)集
onMouseDownEvent: null, //鼠標(biāo)按下時(shí)執(zhí)行的附加事件
onMouseMoveEvent: null, //鼠標(biāo)移動(dòng)時(shí)執(zhí)行的附加事件
onMouseUpEvent: null //鼠標(biāo)釋放時(shí)執(zhí)行的附加事件
}, op || {});
var containerObj = null;
var left = 0;
var top = 0;
init();
function init() {
containerObj = document.getElementById(settings.containerId);
containerObj.style.position = 'absolute';
$(settings.dragIds).each(function () {
$('#' + this).bind('mousedown', function (ev) {
onMouseDown(this, ev);
});
});
}
//鼠標(biāo)左鍵事件
function onMouseDown(o, ev) {
var event = window.event || ev;
if (o.setCapture){
o.setCapture();
//IE下事件綁定
$(o).bind('mousemove', function(ev){
onMouseMove(ev);
});
$(o).bind('mouseup', function(o){
onMouseUp(this);
});
}else if(window.captureEvents){
window.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP);
//Chrome、Firefox下事件綁定
document.addEventListener('mousemove', onMouseMove, true);
document.addEventListener('mouseup', onMouseUp, true);
}
//計(jì)算彈出層的相對(duì)初始位置
left = event.clientX - containerObj.offsetLeft;
top = event.clientY - containerObj.offsetTop;
if(settings.onMouseDownEvent != null){
settings.onMouseDownEvent();
}
}
//鼠標(biāo)移動(dòng)事件
function onMouseMove(ev){
var event = window.event || ev;
if(!event.pageX){
event.pageX = event.clientX;
}
if(!event.pageY){
event.pageY = event.clientY;
}
containerObj.style.left = (event.pageX - left) + 'px';
containerObj.style.top = (event.pageY - top) + 'px';
if(settings.onMouseMoveEvent != null){
settings.onMouseMoveEvent();
}
}
//鼠標(biāo)左鍵釋放事件
function onMouseUp(o){
if (o.releaseCapture){
o.releaseCapture();
//IE下事件釋放
$(o).unbind('mousemove');
$(o).unbind('mouseup');
}else if(window.captureEvents){
window.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP);
//Chrome、Firefox下事件釋放
document.removeEventListener("mousemove", onMouseMove, true);
document.removeEventListener("mouseup", onMouseUp, true);
}
if(settings.onMouseUpEvent != null){
settings.onMouseUpEvent();
}
}
}
})
示例:
<div id="divPopWindow" style="width: 200px; height: 200px;">
<div id="divDragTop" style="width: 100%; height: 24px; background-color: gray; cursor: move;"></div>
<div style="width: 100%; height: 152px; background-color: black;"></div>
<div id="divDragBottom" style="width: 100%; height: 24px; background-color: gray; cursor: move;"></div>
</div>
<script type="text/javascript">
$.ObjMove({
containerId: 'divPopWindow',
dragIds: ['divDragTop', 'divDragBottom']
});
</script>
彈出窗口
$.extend({
OpenWindow: function (op) {
var settings = $.extend({
title: '提示', //彈出窗口標(biāo)題
content: '', //彈出窗口內(nèi)容:內(nèi)容或URL地址
contentType: 'frame', //彈出窗口內(nèi)容區(qū)類型:frame或文本
width: 300, //寬度
height: 300 //高度
}, op || {});
var windowObj = null; //主窗口
var dragTopObj = null; //拖動(dòng)對(duì)象
var shadowObj = null; //陰影對(duì)象
var normalColor = '#336699';
var activeColor = 'orange';
init();
function init() {
windowObj = $('#divPopWindow');
if(windowObj.length == 0){
var content = '';
if(settings.contentType == 'frame') {
content = '<iframe id="divPopWindowFrame" name="divPopWindowFrame" style="width: 100%; height: ' + (settings.height - 20 - 4) + 'px;" frameborder="0px" scrolling="scrolling" src="' + settings.content + '"></iframe>';
} else {
content = settings.content;
}
var fixW = 8; //寬度修正值
if(!$.browser.msie){
fixW = 12;
}
var windowHtml = '<div id="divPopWindow" style="z-index: 1000; width: ' + settings.width + 'px; height: ' + settings.height + 'px; '
+ 'background-color: ' + normalColor + '; color: ' + normalColor + '; font-size: 8pt; font-family: Tahoma; position: absolute; cursor: move; border: 2px solid ' + normalColor + ';">'
+ ' <div id="divPopWindowDragTop" style="background-color: ' + normalColor + '; width: ' + (settings.width - (2 * 2)) + 'px; height: 20px; color: white;" ondblclick="">'
+ ' <span style="float: left; display:block; width: ' + (settings.width - (2 * 12) - 4 - fixW) + 'px; margin-left: 5px; margin-top: 3px">' + settings.title + '</span>'
+ ' <span id="spPopWindowMin" style="width: 12px; border-width: 0px; color: white; font-family: webdings; cursor: default;">0</span>'
+ ' <span id="spPopWindowClose" style="width: 12px; border-width: 0px; color: white; font-family: webdings; cursor: default;">r</span>'
+ ' </div>'
+ ' <div id="divPopWindowContent" style="width: 100%; height: ' + (settings.height - 20) + 'px; background-color: white; line-height: 14px; word-break: break-all;">'
+ ' <div id="divPopWindowContentBox" style="width: 100%; height: ' + (settings.height - 20) + 'px; overflow: auto;">'
+ ' </div>'
+ ' </div>'
+ "</div>"
+ '<div id="divPopWindowShadow" style="display: none; width: ' + settings.width + 'px; height:' + settings.height + 'px; top: 0px; left: 0px; '
+ 'z-index: 999; position: absolute; background-color: black; filter:alpha(opacity=40);">'
+ '</div>';
$(windowHtml).appendTo('body');
$('#spPopWindowMin').bind('click', switchContentArea);
$('#spPopWindowClose').bind('click', close);
}
windowObj = $('#divPopWindow');
dragTopObj = $('#divPopWindowDragTop');
shadowObj = $('#divPopWindowShadow');
$('#divPopWindowContentBox').html(content);
/*初始化窗口容器位置*/
var left = (document.body.clientWidth - settings.width) / 2;
var top = document.documentElement.clientHeight;
var topscroll = document.body.clientHeight;
if (topscroll > top) {
top = topscroll;
}
top = (top - settings.height) / 2;
if (top < 20) {
top = 20;
}
windowObj[0].style.left = left + 'px';
windowObj[0].style.top = top + 'px';
windowObj.show();
$.ObjMove({
containerId: 'divPopWindow',
dragIds: ['divPopWindowDragTop'],
onMouseDownEvent: onMouseDown,
onMouseMoveEvent: onMouseMove,
onMouseUpEvent: onMouseUp
});
}
//鼠標(biāo)按下時(shí)執(zhí)行的事件
function onMouseDown(){
windowObj.css({ backgroundColor: activeColor, borderColor: activeColor});
dragTopObj.css({ backgroundColor: activeColor});
shadowObj.show();
shadowObj[0].style.left = (windowObj.position().left + 12) + 'px';
shadowObj[0].style.top = (windowObj.position().top + 12) + 'px';
}
//鼠標(biāo)移動(dòng)時(shí)執(zhí)行的事件
function onMouseMove(){
shadowObj[0].style.left = (windowObj.position().left + 12) + 'px';
shadowObj[0].style.top = (windowObj.position().top + 12) + 'px';
}
//鼠標(biāo)釋放時(shí)執(zhí)行的事件
function onMouseUp(){
windowObj.css({ backgroundColor: normalColor, borderColor: normalColor});
dragTopObj.css({ backgroundColor: normalColor});
shadowObj.hide();
}
//切換內(nèi)容顯示區(qū)
function switchContentArea(){
if($('#divPopWindowContent').css('display') != 'none'){
$('#divPopWindowContent').hide();
$('#spPopWindowMin').html('2')
windowObj.height(24);
shadowObj.height(24);
}else{
$('#divPopWindowContent').show();
$('#spPopWindowMin').html('0')
windowObj.height(settings.height);
shadowObj.height(settings.height);
}
}
//關(guān)閉窗口
function close(){
windowObj.unbind().hide();
dragTopObj.unbind();
$('#divPopWindowFrame').attr('src', '');
}
}
})
調(diào)用:
$.OpenWindow({
content: 'window.html'
});
表單驗(yàn)證工具類
原理:
利用控件自定義屬性綁定驗(yàn)證類型、提示說(shuō)明,驗(yàn)證時(shí)通過(guò)驗(yàn)證類型調(diào)用驗(yàn)證方法,返回真假值:
function ValidObj(op) {
var obj = new Object;
obj.Valid = valid;
var settings = $.extend({
containerId: 'tbInfo' //容器編號(hào)
}, op);
function valid() {
var isSuccess = 1;
var inputObj = null;
var types = '';
var msgs = '';
$('#' + settings.containerId).find('[valid]').each(function () {
inputObj = $(this);
types = $(eval($(this).attr('valid')));
msgs = $(eval($(this).attr('msg')));
$(eval($(this).attr('valid'))).each(function(n){
isSuccess = run(inputObj, this.toLowerCase());
if(isSuccess == -1){
alert('系統(tǒng)錯(cuò)誤,驗(yàn)證類型不存在,請(qǐng)聯(lián)系開(kāi)發(fā)人員!');
return false;
}
if(isSuccess == 0){
alert(msgs[n]);
inputObj.focus();
return false;
}
});
if(isSuccess != 1){
return false;
}
});
return isSuccess == 1;
}
//運(yùn)行表單驗(yàn)證,返回值:-1 驗(yàn)證類型不存在,0 驗(yàn)證失敗,1 驗(yàn)證成功
function run(o, type) {
var pattern = null;
var val = o.val();
switch (type) {
case 'null':
//為空驗(yàn)證
if ($.trim(val).length == 0) {
return 0;
}
return 1;
case 'numeric':
//數(shù)值驗(yàn)證
pattern = /^[-+]?[0-9]+(\.[0-9]+)?$/;
break;
case 'notchinese':
//不能包含中文驗(yàn)證
pattern = /^[u4E00-u9FA5]+$/;
break;
case 'email':
//郵箱驗(yàn)證
pattern = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
break;
}
if (pattern == null) {
//未找到驗(yàn)證類型
return -1;
}
if (!pattern.test(val)) {
return 0;
}
return 1;
}
return obj;
}
調(diào)用:
<table id="tbTest" cellspacing="1" cellpadding="0" style="background-color: black; width: 100%;">
<tr>
<td>非空及數(shù)值驗(yàn)證</td>
<td><input name="tbNotNullAndNumeric" value="" size="20" valid="['null', 'numeric']" msg="['不能為空,請(qǐng)輸出', '必須為數(shù)值類型,請(qǐng)重新輸入']"></td>
</tr>
<tr>
<td>郵件驗(yàn)證</td>
<td><input name="tbEmail" value="" size="20" valid="['email']" msg="['郵件格式不正確,請(qǐng)重新輸入']"></td>
</tr>
<tr>
<td colspan="2"><input type="button" onclick="Valid();" value="驗(yàn)證輸入框" /></td>
</tr>
</table>
<script type="text/javascript">
function Valid(){
var obj = new ValidObj({
containerId: 'tbTest' //容器編號(hào)
});
if(obj.Valid()){
alert('驗(yàn)證成功。');
}
}
</script>
更多建議: