我试图检测查询有多复杂(就像它只是一个ID选择器,它通过getElementById而不是这样),但这显然没有办法做复杂的CSS查询,并可能会失败某些选择器。如何在IE 7和浏览器6中复制类似于querySelector的东西?
所以我的问题是任何人做了类似的事情,你最终如何为旧版浏览器复制它。
我试图检测查询有多复杂(就像它只是一个ID选择器,它通过getElementById而不是这样),但这显然没有办法做复杂的CSS查询,并可能会失败某些选择器。如何在IE 7和浏览器6中复制类似于querySelector的东西?
所以我的问题是任何人做了类似的事情,你最终如何为旧版浏览器复制它。
为广泛选择的可预测的支持与灒(或jQuery的它使用灒)去
否则,你可以使用代码片段来自: Creating a querySelector for IE that runs at “native speed” - Ajaxian
if (!document.querySelector)
document.querySelector = function(selector) {
var head = document.documentElement.firstChild;
var styleTag = document.createElement("STYLE");
head.appendChild(styleTag);
document.__qsResult = [];
styleTag.styleSheet.cssText = selector + "{x:expression(document.__qsResult.push(this))}";
window.scrollBy(0, 0);
head.removeChild(styleTag);
var result = [];
for (var i in document.__qsResult) {
result.push(document.__qsResult[i]);
}
return result;
}
这段代码不会起作用Bob,我已经在IE7,IE7 IEtester和现代浏览器中测试了它,当'document.querySelector = function ...'重命名为'document.customQuerySelector = function ...'时。具体来说:'styleTag.styleSheet'变成未定义的。 – 2014-07-04 09:58:05
谢谢,我忘了提,我这是为了我个人的项目,我试图尽可能保持轻量级。我可能不得不通过Sizzles源代码看看,但我完全忘了它存在。谢谢! – 2010-10-04 23:23:13