- //获取元素属性
- function getStyle(obj,attr)
- {
- return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj,0)[attr];
- }
- //运动函数
- function doMove(obj,attr,speed,target,endFn)
- {
-
- clearInterval(obj.timer);
- speed = parseInt(getStyle(obj,attr))<target ? speed:-speed;
- //alert(speed);
- obj.timer=setInterval(function(){
- var curPosition=parseInt(getStyle(obj,attr))+speed;
- if(curPosition>target && speed>0 || curPosition<target && speed<0)
- curPosition=target;
- obj.style[attr]=curPosition + ‘px‘;
- if(curPosition==target)
- {
- clearInterval(obj.timer);
- endFn && endFn();
- }
- },50);
- }
- //getElementByClassName函数
- function getElementByClassName(parent,tagName,className)
- {
- var aEls=parent.getElementsByTagName(tagName);
- var arr=[];
- for(var i=0;i<aEls.length;i++)
- {
- var arrClassName=aEls[i].className.split(‘ ‘);
- var _index=arrIndexOf(arrClassName,className);
- if(_index != -1){
- arr.push(aEls[i]);
- }
- }
- return arr;
- }
- //removeClass函数
- function removeClass(obj,className)
- {
- //如果原来有class
- if(obj.className!=‘‘){
- var arrClassName=obj.className.split(‘ ‘);
- var _index=arrIndexOf(arrClassName,className);
- if(_index != -1){
- arrClassName.splice(_index,1); //删除需要删除的calss
- obj.className=arrClassName.join(‘ ‘); //然后将arrClassName数组拼接起来
- }
- }
- }
- //绑定事件函数
- function bind(obj,evname,fn){
- if(obj.addEventListener){
- obj.addEventListener(evname,fn,false);
- }else{
- obj.attachEvent(‘on‘+evname,function(){
- fn.call(obj);
- //fn()==fn.call() call(第一个参数,第二个参数) call函数可以改变函数this的指向,call函数传入的第一个参数就是改变this指向的值,call的第二第三个参数就是原函数的参数
- });
- }
- }
- //鼠标在可视区域内的拖拽
- function clientDrag(obj){
- obj.onmousedown=function(ev){
- ev=ev || event;
- var ms_b=ev.clientX-obj.offsetLeft;
- var ms_t=ev.clientY-obj.offsetTop;
- document.onmousemove=function(ev){
- ev=ev || event;
- var currX=ev.clientX-ms_b;
- var currY=ev.clientY-ms_t;
- var Width=document.body.clientWidth || document.documentElement.cilentWidth;
- var Height=document.body.clientHeight || document.documentElement.cilentHeight;
- if(currX<0) {currX=0;}
- else if(currX>Width-obj.clientWidth){
- currX=Width-obj.clientWidth;
- }
- if(currY<0) {currY=0;}
- else if(currY>Height-obj.clientHeight){
- currY=Height-obj.clientHeight;
- }
- obj.style.left=currX +‘px‘;
- obj.style.top=currY +‘px‘;
- return false;
- }
- document.onmouseup=function(){
- document.onmousemove=document.onmouseup=null;
- }
- }
- }
常用JS函数封装
原文:http://www.cnblogs.com/beta-data/p/4559215.html