平时总结的一些常用javascript函数封装:
1 //获取样式 2 function getStyle(obj,name){ 3 if(obj.currentStyle){ 4 return obj.currentStyle[name]; 5 } 6 else{ 7 return getComputedStyle(obj,false)[name]; 8 } 9 } 10 11 //获取鼠标的位置 12 function getPos(ev){ 13 var scrollTop = document.documentElement.scrollTop || document.body.scrollTop; 14 var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft; 15 return{x:ev.clientX+scrollLeft,y:ev.clientY+scrollTop} //以一个json的形式返回 16 17 } 18 19 //通过className选择元素 20 function getByClass(oParent,sClass){ 21 var aResult = []; 22 var aEle = oParent.getElementsByTagName('*'); 23 for(var i=0; i<aEle.length; i++){ 24 if(aEle[i].className == sClass){ 25 aResult.push(aEle[i]); 26 } 27 28 } 29 return aResult; //返回一个数组 30 31 } 32 33 //完美运动框架 34 function startMove(obj,json,fnEnd){ 35 36 clearInterval(obj.timer); 37 obj.timer=setInterval(function(){ 38 var bStop=true; //这一次运动就结束了---所有值都已经到了 39 for(var attr in json){/// 40 41 //1.取当前的值 42 var cur = 0; 43 if(attr == 'opacity'){ 44 cur = Math.round((parseFloat(getStyle(obj,attr)))*100); 45 } 46 else{ 47 cur = parseInt(getStyle(obj,attr)); 48 } 49 50 //2.算速度 51 var speed = (json[attr]-cur)/6; 52 speed = speed>0?Math.ceil(speed):Math.floor(speed); 53 54 //3.检测停止 55 if(cur != json[attr]){ 56 bStop = false; 57 } 58 if(attr == 'opacity'){ 59 obj.style.filter = 'alpha(opacity:'+(cur+speed)+')'; 60 obj.style.opacity = (cur+speed)/100; 61 }else{ 62 obj.style[attr] = cur + speed + 'px'; 63 } 64 }/// 65 66 if(bStop){ 67 clearInterval(obj.timer); 68 if(fnEnd) fnEnd; 69 } 70 },30); 71 } 72 73 //事件绑定函数 74 function myAddEvent(obj,ev,fn){ 75 if(obj.attachEvent){ 76 obj.attachEvent('on'+ev,fn); 77 } 78 else{ 79 obj.addEventListener(ev,fn,false); 80 } 81 } 82 83 //全兼容的 事件绑定 and 阻止默认事件 84 var EventUtil = { 85 //Notice: type is not include 'on', for example: click mouseover mouseout and so on 86 addHandler: function(element, type, handler){ 87 if (element.addEventListener){ 88 element.addEventListener(type, handler, false); 89 } else if(element.attachEvent){ 90 element.attachEvent('on'+type, handler); 91 } else { 92 element['on'+type] = handler; 93 } 94 }, 95 96 preventDefault: function(event){ 97 if(event.preventDefault){ 98 event.preventDefault(); 99 }else{ 100 event.returnValue = false; 101 } 102 } 103 }; 104 105 //ajax函数 106 function ajax(url,fnSucc,fnFaild){ 107 //1.创建Ajax对象 108 if(window.XMLHttpRequest){ 109 var oAjax = new XMLHttpRequest(); 110 } 111 else{ 112 var oAjax = new ActiveXObject("Microsoft.XMLHttp"); 113 114 } 115 //2.连接服务器 116 oAjax.open('GET',url,true); 117 //3.发送请求 118 oAjax.send(); 119 //4.接受返回值 120 oAjax.onreadystatechange = function(){ 121 if(oAjax.readyState == 4){ //读取完成 122 if(oAjax.status == 200){ //成功 123 fnSucc(oAjax.responseText); 124 } 125 else{ 126 if(fnFaild){ //传进来了才会用 127 fnFaild(oAjax.status); 128 } 129 } 130 } 131 }; 132 }