当前位置:首页 > querySelector querySelectorAll 兼容处理,让ie支持querySelector 和 querySelectorAll

querySelector querySelectorAll 兼容处理,让ie支持querySelector 和 querySelectorAll

发布于 2018-06-04 阅读 713 次 浏览器兼容

在简书上看到的这段兼容代码,看不太懂,先收藏起来了,欢迎大牛抛转解释

  1. if (!document.querySelectorAll) {
  2. document.querySelectorAll = function (selectors) {
  3. var style = document.createElement('style'), elements = [], element;
  4. document.documentElement.firstChild.appendChild(style);
  5. document._qsa = [];
  6. style.styleSheet.cssText = selectors + '{x-qsa:expression(document._qsa && document._qsa.push(this))}';
  7. window.scrollBy(0, 0);
  8. style.parentNode.removeChild(style);
  9. while (document._qsa.length) {
  10. element = document._qsa.shift();
  11. element.style.removeAttribute('x-qsa');
  12. elements.push(element);
  13. }
  14. document._qsa = null;
  15. return elements;
  16. };
  17. }
  18. if (!document.querySelector) {
  19. document.querySelector = function (selectors) {
  20. var elements = document.querySelectorAll(selectors);
  21. return (elements.length) ? elements[0] : null;
  22. };
  23. }
  24. // 用于在IE6和IE7浏览器中,支持Element.querySelectorAll方法
  25. var qsaWorker = (function () {
  26. var idAllocator = 10000;
  27. function qsaWorkerShim(element, selector) {
  28. var needsID = element.id === "";
  29. if (needsID) {
  30. ++idAllocator;
  31. element.id = "__qsa" + idAllocator;
  32. }
  33. try {
  34. return document.querySelectorAll("#" + element.id + " " + selector);
  35. }
  36. finally {
  37. if (needsID) {
  38. element.id = "";
  39. }
  40. }
  41. }
  42. function qsaWorkerWrap(element, selector) {
  43. return element.querySelectorAll(selector);
  44. }
  45. // Return the one this browser wants to use
  46. return document.createElement('div').querySelectorAll ? qsaWorkerWrap : qsaWorkerShim;
  47. })();

出处链接:https://www.jianshu.com/p/872d69047dda

相关文章