Home  >  Article  >  Web Front-end  >  Some commonly used JS functions (updated on 2009-06-04)_javascript skills

Some commonly used JS functions (updated on 2009-06-04)_javascript skills

WBOY
WBOYOriginal
2016-05-16 18:51:44925browse
Copy code The code is as follows:

//获取对象
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            {
                try{
                    if(allScripts[i].src.indexOf(filename)>-1)
                    {
                        had = true;
                        break;
                    }
                }catch(e){}
            }    
        }
        if(!had)
        {
            document.write("");
        }
    }else
    {
        if(chkonce)
        {
            var allCss = document.getElementsByTagName("link");
            if(allCss.length)
            {
                for(var i=0;i                {
                    try{
                        if(allCss[i].href.indexOf(filename)>-1)
                        {
                            had = true;
                            break;
                        }
                    }catch(e){}
                }
            }
        }
        if(!had)
        {
            document.write("");
        }
    }
}
//定义根目录路径
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    {
        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    {
        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 {
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




*/
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("出错!The size of the image you uploaded is " (parseInt(img.fileSize/1024)) "KB, which exceeds the limit of " size "KB, please re-upload"); ;
}
return true;
}
//Detect client environment
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 "other";
}

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)
                                                                                                                                                                                                                         -1)
                                                                                                                                                                                                                                                                                    🎜>                                                                                                                                                               var _winName = Array('2000','XP','2003') ;
                  var _ntNum = appVer.match(/Windows NT 5.d/i).toString();                                               $1")];
     }catch(e){return 'Windows';}
     }
    }else if(_pf == "Mac68K" || _pf == "MacPPC" || _pf == "Macintosh")
                                                   Unix";
}else if(String (_pf).indexOf("Linux") > -1)
                                                                                     ;                                                         > }

this.OS = me.GetOSInfo(); //Operating system type
this.IeVer = null;
this.Bs_lang = (navigator.appName == 'Netscape'?navigator.language :navigator.browserLanguage); // Browser language version
this.Bs_Name = me.GetBrowserName(); // Browser name

// Browser version
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;
}
//Client information
var CMInfo = new ClientMentInfo();
//Cache background image under IE6
if(CMInfo.Ie6)
{
Document.execCommand("BackgroundImageCache", false, true);
}
//Set all checkboxes to be selected or unchecked
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 )
                                                                                                                 {
for(var i=0; i<_arr.length; i )
                                                                                                                                   🎜>                                                               !_arr.length ) // There is only one checkbox, then length = undefined
_arr.checked = false; _arr.length; i )
                                                                                                                                  🎜> }
}

//Make the current page jump Go to the specified page number page
function goPage(pageNum,pageStr)
{
window.location.href = "?np=" pageNum pageStr;
}
//Go to the strings respectively Before and after, left and right spaces
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,"")}


Pay attention to globalPara.js, which is a file of common variables and constants used by each website. If you don’t need such a file, you can put
//JS for loading public variables
loadjscssfile(JS_PATH "globalPara.js");

Delete these two sentences, otherwise an error will be reported.

(updated on 2009-06-04)
Changed the ClientMentInfo class to be compatible with IE6, IE7, IE8, Vista, Windows 7 and Firefox
Statement:
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