IE 6、IE 7互換querySelectorAllおよびquerySelectorメソッド-最終バージョン

4787 ワード

querySelectorおよびquerySelectorAllメソッドは、W 3 C Selectors API仕様で定義されています.彼らの役割はCSSセレクタの仕様に基づいて、ドキュメントに指定された要素を簡単に位置決めすることです.現在、ほとんどの主流ブラウザでサポートされています.IE 8(含む)以上のバージョン、Firefox、Chrome、Safari、Operaを含む.
QuerySelectorとquerySelectorAllの方法は使いやすいですが、残念ながらIE 6、IE 7はサポートされていません.IE 6、IE 7もquerySelectorAllとquerySelectorの2つの方法をサポートするには、次のコードを見てください.
if (!document.querySelectorAll) {

    document.querySelectorAll = function (selectors) {

        var style = document.createElement('style'), elements = [], element;

        document.documentElement.firstChild.appendChild(style);

        document._qsa = [];



        style.styleSheet.cssText = selectors + '{x-qsa:expression(document._qsa && document._qsa.push(this))}';

        window.scrollBy(0, 0);

        style.parentNode.removeChild(style);



        while (document._qsa.length) {

            element = document._qsa.shift();

            element.style.removeAttribute('x-qsa');

            elements.push(element);

        }

        document._qsa = null;

        return elements;

    };

}



if (!document.querySelector) {

    document.querySelector = function (selectors) {

        var elements = document.querySelectorAll(selectors);

        return (elements.length) ? elements[0] : null;

    };

}



//    IE6 IE7    ,  Element.querySelectorAll  

var qsaWorker = (function () {

    var idAllocator = 10000;



    function qsaWorkerShim(element, selector) {

        var needsID = element.id === "";

        if (needsID) {

            ++idAllocator;

            element.id = "__qsa" + idAllocator;

        }

        try {

            return document.querySelectorAll("#" + element.id + " " + selector);

        }

        finally {

            if (needsID) {

                element.id = "";

            }

        }

    }



    function qsaWorkerWrap(element, selector) {

        return element.querySelectorAll(selector);

    }



    // Return the one this browser wants to use

    return document.createElement('div').querySelectorAll ? qsaWorkerWrap : qsaWorkerShim;

})();

 
参考資料:
   qsa-polyfill-ie7.js    How to add querySelectorAll() function to Element for IE <= 7?    querySelector.polyfill.js