一些常用且实用的原生 JavaScript函数

一些常用且实用的原生 JavaScript函数 日常开始中常用到的一些原生JavaScript函数,比较实用, 今天特地整理一下,分享给大家,希望对大家有用,会常更新,同时也欢迎大家补充. css及html方面的技巧总结,点此前往: 前端开发中一些常用技巧总结.

1. document.getElementById的简写: http://mrthink.net/javascript-getbyid-simplewrite/;

2. getElementsByTagName的简写方式: http://mrthink.net/javascrip-simple-getelementsbytagname/;

3. 原生JavaScript中获取元素索引的函数: http://mrthink.net/javascript-index-functio/;

 4. 替代window.onload,可多次调用的加载函数:

function iLoad(func) { var oLoad=window.onload; if(typeof window.onload!='function'){ window.onload=func; }else{ window.onload=function(){ oLoad(); func(); } } }

5. 获取下一个元素节点:

function nextElem(node){ if(node.nodeType==1) return node; if(node.nextSibling) return nextElem(node.nextSibling); return null; }

 6. 获取上一个元素节点(此函数须调用第五条中的函数):

 function prevElem(node){ if(node.nodeType==1){ return node; }else if(node.previousSibling){ return nextElem(node.previousSibling); }else{ return null; } }

7. 原生JavaScript中有insertBefore方法,可惜却没有insertAfter方法,怎么办?用如下函数实现:

function insertAfter(newChild,refChild){ var parElem=refChild.parentNode; if(parElem.lastChild==refChild){ refChild.appendChild(newChild); }else{ parElem.insertBefore(newChild,refChild.nextSibling); } }

8. 为元素添加样式[记住是添加不是替换,相当于jQuery中的addClass(value)]:

 function addClass(elem,value){ if(!elem.className){ elem.className=value; }else{ var oValue=elem.className; oValue+=" "; oValue+=value; elem.className=oValue; } }

 9. 获取元素的样式:

function getStyle(id,stylename){ var elem=$(id); var realStyle=null; if(elem.currentStyle){ realStyle=elem.currentStyle[stylename]; }else if(window.getComputedStyle){ realStyle=window.getComputedStyle(elem,null)[stylename]; } return realStyle; }

 9. 兼容事件绑定: function addEventSamp(obj,evt,fn){ if (obj.addEventListener) { obj.addEventListener(evt, fn, false); }else if(obj.attachEvent){ obj.attachEvent('on'+evt,fn); } }

10. 移除事件 function removeEventSamp(obj,evt,fn){ if(obj.removeEventListener){ obj.removeEventListener(evt,fn,false); }else if(obj.detachEvent){ obj.detachEvent('on'+evt,fn); } }

posted @ 2010-09-08 10:25  Eric.Wang  阅读(240)  评论(0编辑  收藏  举报