常用js函数汇总

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/
function getElementsByClassName(oElm, strTagName, strClassName){
var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
strClassName = strClassName.replace(/\-/g, "\\-");
var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
var oElement;
for(var i=0; i<arrElements.length; i++){
oElement = arrElements[i];
if(oRegExp.test(oElement.className)){
arrReturnElements.push(oElement);
}
}
return (arrReturnElements)
}

//http://www.bigbold.com/snippets/posts/show/2630
function addClassName(objElement, strClass, blnMayAlreadyExist){
if ( objElement.className ){
var arrList = objElement.className.split(' ');
if ( blnMayAlreadyExist ){
var strClassUpper = strClass.toUpperCase();
for ( var i = 0; i < arrList.length; i++ ){
if ( arrList[i].toUpperCase() == strClassUpper ){
arrList.splice(i, 1);
i--;
}
}
}
arrList[arrList.length] = strClass;
objElement.className = arrList.join(' ');
}
else{
objElement.className = strClass;
}
}

//http://www.bigbold.com/snippets/posts/show/2630
function removeClassName(objElement, strClass){
if ( objElement.className ){
var arrList = objElement.className.split(' ');
var strClassUpper = strClass.toUpperCase();
for ( var i = 0; i < arrList.length; i++ ){
if ( arrList[i].toUpperCase() == strClassUpper ){
arrList.splice(i, 1);
i--;
}
}
objElement.className = arrList.join(' ');
}
}

//http://ejohn.org/projects/flexible-javascript-events/
function addEvent( obj, type, fn ) {
if ( obj.attachEvent ) {
obj["e"+type+fn] = fn;
obj[type+fn] = function() { obj["e"+type+fn]( window.event ) };
obj.attachEvent( "on"+type, obj[type+fn] );
}
else{
obj.addEventListener( type, fn, false );
}
}
//http://www.quirksmode.org/dom/getstyles.html
function getStyle(el,styleProp)
{
var x = document.getElementById(el);
if (x.currentStyle)
var y = x.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
return y;
}

//判断浏览器
var isFF=(navigator.userAgent.toLowerCase().indexOf("firefox")!=-1);
var isIE=(navigator.userAgent.toLowerCase().indexOf("msie")!=-1);
var isIE8=(navigator.userAgent.toLowerCase().indexOf("msie 8")!=-1);