Created
November 13, 2012 08:15
-
-
Save andy12530/4064621 to your computer and use it in GitHub Desktop.
为不支持的浏览器添加getElementsByClassName与querySelectorAll方法
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
document.getElementById(); | |
document.getElementsByTagName(); | |
document.getElementsByName(); | |
以上三种方法在主流浏览器中得到原生支持,但是通过class取得元素以及通过css选择器的方式取得元素,即 | |
getElementsByClassName与querySelectorAll未在IE6、7、8中得到完全支持 | |
*/ | |
function each(elem, callback) { | |
if (elem.length !== undefined) { | |
for(var i=0, len = elem.length; i<len; i++) { | |
if (callback.call(elem[i], i, elem[i]) === false) | |
break; | |
} | |
} else { | |
for(name in elem) { | |
callback.call(elem[name], name, elem[name]); | |
} | |
} | |
} | |
function getClass(className, elem) { | |
var elem = elem || document; | |
if (document.getElementsByClassName) { | |
return elem.getElementsByClassName(className); | |
} else { | |
var rs = []; | |
each(elem.getElementsByTagName("*"), function(i) { | |
if (/\b+ className +\b/.test(this.className)) { | |
rs.push(this); | |
} | |
}) | |
return rs; | |
} | |
} | |
/* | |
动态添加一张样式表(document.createStyleSheet(),chrome不支持),用选择器添加一条规则,然后拿出符合规则的元素, | |
清空样式表。 | |
原因:querySelectorAll仅在ie6/7上不支持。 | |
*/ | |
function getQuerySelectorAll(selector) { | |
if (document.querySelectorAll) { | |
return documnet.querySelectorAll(selector); | |
} else { | |
var styleSheet = document.createStyleSheet(), rs = []; | |
styleSheet.addRule(selector, "a:b"); | |
each(document.getElementsByTagName("*"), function(i) { | |
if (this.currentStyle.a === 'b') { | |
rs.push(this); | |
} | |
}) | |
styleSheet.cssText = ''; | |
return rs; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
参考qatrix.js中的一些方法。