一些常用的JS功能函数(2009-06-04更新)


Posted in Javascript onJune 04, 2009
//获取对象 
function getObject(objectId,top) 
{ 
    doc = top?window.top.document:document; 
    if(typeof(objectId)!="object" && typeof(objectId)!="function") 
    { 
        if(doc.getElementById && doc.getElementById(objectId)) 
         { 
         // W3C DOM 
         return doc.getElementById(objectId); 
         } 
        else if(doc.getElementsByName(objectId)) 
        { 
            return doc.getElementsByName(objectId)[0]; 
        } 
         else if (doc.all && doc.all(objectId)) 
         { 
         // MSIE 4 DOM 
         return doc.all(objectId); 
         } 
         else if (doc.layers && doc.layers[objectId]) 
         { 
         // NN 4 DOM.. note: this won't find nested layers 
         return doc.layers[objectId]; 
         } 
         else 
         { 
         return false; 
         } 
    }else 
        return objectId; 
} 
//获取相对路径 
function getRelativePath() 
{ 
    var url = location.href;//当前url 
    var urlcs = String(location.search); 
    url = url.replace(urlcs,""); 
    var path = url.length - url.replace(/\//g,"").length - 3;    //层次为url包含/的长度-没有包含/的长度再减去项目头/的个数     var str = ""; 
    for(var i = 0; i < path; i++) 
    { 
     str += "../";//组合成一个相对路径的字符串返回 
    } 
    return str; 
} 
//加载其他JS文件或CSS文件 
function loadjscssfile(filename,filetype,chkonce) 
{ 
    filetype = !filetype?"js":filetype; 
    var had = false; 
    if(filetype=="js") 
    { 
        if(chkonce) 
        { 
            var allScripts = document.getElementsByTagName("script"); 
            for(var i=0;i<allScripts.length;i++) 
            { 
                try{ 
                    if(allScripts[i].src.indexOf(filename)>-1) 
                    { 
                        had = true; 
                        break; 
                    } 
                }catch(e){} 
            }     
        } 
        if(!had) 
        { 
            document.write("<script src=""+filename+"" src=""+filename+"" type='text/javascript'></script>"); 
        } 
    }else 
    { 
        if(chkonce) 
        { 
            var allCss = document.getElementsByTagName("link"); 
            if(allCss.length) 
            { 
                for(var i=0;i<allCss.length;i++) 
                { 
                    try{ 
                        if(allCss[i].href.indexOf(filename)>-1) 
                        { 
                            had = true; 
                            break; 
                        } 
                    }catch(e){} 
                } 
            } 
        } 
        if(!had) 
        { 
            document.write("<link type='text/css' rel='stylesheet' href=""+filename+"" href=""+filename+"" />"); 
        } 
    } 
} 
//定义根目录路径 
var ROOT_PATH = getRelativePath(); 
var JS_PATH = ROOT_PATH+'js/'; 
var AJAX_PATH = ROOT_PATH+'ajax/'; 
var CSS_PATH = ROOT_PATH+'css/'; 
var IMAGES_PATH = ROOT_PATH+'images/'; 
var EDITOR_PATH = ROOT_PATH+'uploadeditor/'; 
var PUB_PATH = ROOT_PATH+'uploadfile/'; 
//加载公共变量的JS 
loadjscssfile(JS_PATH+"globalPara.js"); 
//设置下拉表中某一项被选中 
function setSelOption(objId,vlu) 
{ 
    objId = getObject(objId); 
    for(var i=0;i<objId.options.length;i++) 
    { 
        if(objId.options[i].value==vlu) 
        { 
            objId.options[i].setAttribute("selected","selected"); 
            break; 
        } 
    } 
} 
//根据下拉表中的option文本设置某一项被选中 
function setTxtOption(objId,txt) 
{ 
    objId = getObject(objId);         
    for(var i=0;i<objId.options.length;i++) 
    { 
        if(objId.options[i].innerHTML==txt) 
        { 
            objId.options[i].setAttribute("selected","selected"); 
            break; 
        } 
    }     
} 
//设置单选按钮组中某一项被选中 
function setSelRadio(objName,vlu) 
{ 
    objName = document.getElementsByName(objName); 
    for(var i=0;i<objName.length;i++) 
    { 
        if(objName[i].value==vlu) 
        { 
            objName[i].setAttribute("checked","checked"); 
            break; 
        } 
    } 
} 
//根据ID设置复选框中某些项被选中 
//vlu 的格式为 : 1,2,3 
function setSelCheckbox(prefix,vlu) 
{ 
    var _arr = vlu.split(","); 
    if(_arr!="") 
    { 
        for(var i=0; i<_arr.length; i++) 
        { 
            getObject(prefix+_arr[i]).checked = true; 
        } 
    } 
} 
//快捷输入,fromObj:来源对象,toObjId:目标对象的ID,txt为true时取toObjId的innerHTML值 
function fastInput(fromObj,toObjId,txt) 
{ 
    if(fromObj.value=='' || fromObj.value==0) return false; 
    txt = !txt ? false : txt; 
    var toObj = getObject(toObjId); 
    if(txt) 
    { 
        if(typeof (toObj.value) == 'undefined') 
             toObj.innerHTML = toTxt(fromObj.options[fromObj.selectedIndex].innerHTML); 
        else 
            toObj.value = toTxt(fromObj.options[fromObj.selectedIndex].innerHTML); 
    }else 
    { 
        if(typeof (toObj.value) == 'undefined') 
             toObj.innerHTML = fromObj.value; 
        else 
            toObj.value = fromObj.value;         
    } 
} 
/* 
IE6,IE7上传图片前预览图片 
IE6下还可以同时检测图片的大小 
size 单位为KB 
<style type="text/css"><!-- 
.newPreview 
{ 
    width:400px; height:300px; 
    FILTER: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale) 
} 
.nodis{display:none;} 
--></style><style type="text/css" bogus="1"> 
.newPreview 
{ 
    width:400px; height:300px; 
    FILTER: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale) 
} 
.nodis{display:none;}</style> 
<input type="file" name="litpic" onchange="PreviewImg(this,'newPreview','ndsPreview',400)" /> 
<div id="newPreview" class="newPreview"></div> 
<img id="ndsPreview" class="nodis" /> 
*/ 
function PreviewImg(imgFile,newPreview,ndsPreview,size) 
{ 
    newPreview = getObject(newPreview); 
    if(!imgFile || !imgFile.value || !newPreview){return}; 
    var patn = /\.jpg$|\.jpeg$|\.gif$|\.png$|\.bmp$/i; 
    if(patn.test(imgFile.value)) 
    { 
        try{newPreview.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgFile.value;}catch(e){} 
        if(navigator.appVersion.indexOf("MSIE 6.0",0)>-1) 
        { 
            size=!size?0:size; 
            ndsPreview = getObject(ndsPreview); 
            if(ndsPreview) 
            { 
                try{ndsPreview.attachEvent("onreadystatechange", function(){checkImgSize(ndsPreview,size)})}catch(e){} 
                ndsPreview.src = imgFile.value; 
            } 
        } 
    } 
    else 
    { 
        alert("您选择的不是图像文件,请重新选择."); 
    } 
} 
function PreviewImgNow(imgDiv,imgFile) 
{ 
    try{getObject(imgDiv).filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgFile}catch(e){}     
} 
//上传之前检测图片的大小 
//条件是在file改变时要触发函数将缩略图显示在img上 
//size 单位为KB 
function checkImgSize(img,size) 
{ 
    img = getObject(img); 
    if(img.readyState == "complete") 
    { 
        var limit = size * 1024; 
        if(img.fileSize > limit) 
        { 
            alert("出错!您上传的图片大小为"+(parseInt(img.fileSize/1024))+"KB,超过了"+size+"KB的限制,请重新上传"); 
            return false 
        }else 
            return true; 
    } 
    return true; 
} 
//检测客户端环境 
function ClientMentInfo() 
{ 
    var me = this;     
    var appVer = navigator.userAgent; 
    this.GetBrowserName = function (){ 
        if(appVer.indexOf("MSIE")>0) return "IE"; 
        else if(appVer.indexOf("Firefox")>0) return "Firefox"; 
        else if(appVer.indexOf("Chrome")>0) return "Chrome"; 
        else if(appVer.indexOf("Safari")>0) return "Safari"; 
        else if(appVer.indexOf("Camino")>0) return "Camino"; 
        else if(appVer.indexOf("Konqueror")>0) return "Konqueror"; 
        else return "其它"; 
    } 
    this.GetOSInfo = function (){ 
        var _pf = navigator.platform; 
        if(_pf == "Win32" || _pf == "Windows") 
        { 
            if(appVer.indexOf("Windows NT 6.0") > -1 || appVer.indexOf("Windows Vista") > -1) 
            { 
                return 'Windows Vista';     
            }else if(appVer.indexOf("Windows NT 6.1") > -1 || appVer.indexOf("Windows 7") > -1) 
            { 
                return 'Windows 7';     
            }else 
            { 
                try{ 
                    var _winName = Array('2000','XP','2003'); 
                    var _ntNum = appVer.match(/Windows NT 5.\d/i).toString(); 
                    return 'Windows ' + _winName[_ntNum.replace(/Windows NT 5.(\d)/i,"$1")]; 
                }catch(e){return 'Windows';} 
            } 
        }else if(_pf == "Mac68K" || _pf == "MacPPC" || _pf == "Macintosh") 
        { 
            return "Mac";             
        }else if(_pf == "X11") 
        { 
            return "Unix";     
        }else if(String(_pf).indexOf("Linux") > -1) 
        { 
            return "Linux";     
        }else 
        { 
            return "Unknow";     
        }         
    } 
    this.OS = me.GetOSInfo();        //操作系统类型 
    this.IeVer = null; 
    this.Bs_lang = (navigator.appName == 'Netscape'?navigator.language:navigator.browserLanguage);//浏览器语言版本 
    this.Bs_Name = me.GetBrowserName();        //浏览器名称 
    //浏览器版本 
    if(this.Bs_Name=='IE') 
    { 
        var _msie = appVer.match(/MSIE \d./i).toString(); 
        this.Bs_Version = this.IeVer = _msie.replace(/MSIE (\d)./i,"$1"); 
    }else 
    { 
        this.Bs_Version = appVer; 
    } 
    this.Ie6 = this.IeVer==6 ? true: false; 
    this.Ie7 = this.IeVer==7 ? true: false; 
    this.Ie8 = this.IeVer==8 ? true: false; 
} 
//客户端信息 
var CMInfo = new ClientMentInfo(); 
//IE6 下缓存背景图片 
if(CMInfo.Ie6) 
{ 
    document.execCommand("BackgroundImageCache", false, true); 
} 
//设置复选框全选或全不选 
function setAllCheckbox(formName,objName,num) 
{ 
    if(formName) 
        _arr = getObject(formName).elements[objName]; 
    else 
        _arr = typeof(objName)=="object"?objName:document.all(objName); 
    if(_arr) 
    { 
        if(num) 
        { 
            if (!_arr.length ) // 只有一个复选框,则length = undefined 
                _arr.checked = true; 
            else 
            { 
                for(var i=0; i<_arr.length; i++) 
                { 
                    _arr[i].checked = true; 
                } 
            } 
        }else 
        { 
            if (!_arr.length ) // 只有一个复选框,则length = undefined 
                _arr.checked = false; 
            else 
            { 
                for(var i=0; i<_arr.length; i++) 
                { 
                    _arr[i].checked = false; 
                } 
            } 
        } 
    } 
} 
//使当前页面跳到指定的页数页面 
function goPage(pageNum,pageStr) 
{ 
    window.location.href = "?np="+pageNum+pageStr; 
} 
//分别去字符串前后,左边,右边空格 
String.prototype.trim = function(){ return this.replace(/^\s+|\s+$/g,"")} 
String.prototype.ltrim = function(){ return this.replace(/^\s+/g,"")} 
String.prototype.rtrim = function(){ return this.replace(/\s+$/g,"")}

注意globalPara.js本作者常用到的一些每个站自己的常用变量和常量的文件,如果你不需要这样的文件,可把
//加载公共变量的JS
loadjscssfile(JS_PATH+"globalPara.js");

这两句删掉,不然会报错。

(2009-06-04更新)
将 ClientMentInfo类改成了兼容IE6,IE7,IE8,Vista,Windows 7和Firefox

Javascript 相关文章推荐
地址栏传递中文参数乱码在js里用escape转码
Aug 28 Javascript
同步文本框内容JS代码实现
Aug 04 Javascript
ES6新特征数字、数组、字符串
Oct 01 Javascript
JavaScript 闭包机制详解及实例代码
Oct 10 Javascript
js模式化窗口问题![window.dialogArguments]
Oct 30 Javascript
Bootstrap 3浏览器兼容性问题及解决方案
Apr 11 Javascript
easyUI下拉列表点击事件使用方法
May 18 Javascript
BootStrap Fileinput插件和Bootstrap table表格插件相结合实现文件上传、预览、提交的导入Excel数据操作步骤
Aug 07 Javascript
基于Vue的SPA动态修改页面title的方法(推荐)
Jan 02 Javascript
JS兼容所有浏览器的DOMContentLoaded事件
Jan 12 Javascript
深入理解Vue Computed计算属性原理
May 29 Javascript
修改vue+webpack run build的路径方法
Sep 01 Javascript
javascript globalStorage类代码
Jun 04 #Javascript
IE8 兼容性问题(属性名区分大小写)
Jun 04 #Javascript
JavaScript效率调优经验
Jun 04 #Javascript
cookie丢失问题(认证失效) Authentication (用户验证信息)也会丢失
Jun 04 #Javascript
javascript 常用方法总结
Jun 03 #Javascript
Javascript 获取字符串字节数的多种方法
Jun 02 #Javascript
javascript HTMLEncode HTMLDecode的完整实例(兼容ie和火狐)
Jun 02 #Javascript
You might like
PHP中的string类型使用说明
2010/07/27 PHP
发款php蜘蛛统计插件只要有mysql就可用
2010/10/12 PHP
PHP SPL使用方法和他的威力
2013/11/12 PHP
PHP判断用户是否已经登录(跳转到不同页面或者执行不同动作)
2016/09/22 PHP
PHP数组操作简单案例分析
2016/10/15 PHP
php微信公众号开发模式详解
2016/11/28 PHP
js 键盘记录实现(兼容FireFox和IE)
2010/02/07 Javascript
通过jquery的$.getJSON做一个跨域ajax请求试验
2011/05/03 Javascript
用dtree实现树形菜单 dtree使用说明
2011/10/17 Javascript
JSON传递bool类型数据的处理方式介绍
2013/09/18 Javascript
javascript中通过arguments参数伪装方法重载
2014/10/08 Javascript
Javascript中引用类型传递的知识点小结
2017/03/06 Javascript
webpack4.0打包优化策略整理小结
2018/03/30 Javascript
vue 中filter的多种用法
2018/04/26 Javascript
浅析vue插槽和作用域插槽的理解
2019/04/22 Javascript
关于vue3默认把所有onSomething当作v-on事件绑定的思考
2020/05/15 Javascript
[02:01]BBC DOTA2国际邀请赛每日综述:八强胜者组鏖战,中国队喜忧参半
2014/07/19 DOTA
python生成随机密码或随机字符串的方法
2015/07/03 Python
python TCP Socket的粘包和分包的处理详解
2018/02/09 Python
python2.7无法使用pip的解决方法(安装easy_install)
2018/04/03 Python
浅谈python连续赋值可能引发的错误
2018/11/10 Python
python flask框架实现传数据到js的方法分析
2019/06/11 Python
python实现淘宝购物系统
2019/10/25 Python
numpy.array 操作使用简单总结
2019/11/08 Python
使用Python串口实时显示数据并绘图的例子
2019/12/26 Python
浅谈keras中loss与val_loss的关系
2020/06/22 Python
基础的CSS3弹性盒Flexbox布局使用实例
2016/04/08 HTML / CSS
HTML5使用DOM进行自定义控制示例代码
2013/06/08 HTML / CSS
西班牙太阳镜品牌:Hawkers
2018/03/11 全球购物
思想品德自我鉴定
2013/10/12 职场文书
我们的节日清明节活动总结
2014/04/30 职场文书
门市房租房协议书
2014/12/04 职场文书
校运会通讯稿
2015/07/18 职场文书
教师教育教学随笔
2015/08/15 职场文书
Python制作一个随机抽奖小工具的实现
2021/07/07 Python
Redis实现主从复制方式(Master&Slave)
2022/06/21 Redis