【问题标题】:How to support .closest in IE11如何在 IE11 中支持 .closest
【发布时间】:2020-04-14 17:33:21
【问题描述】:

我正在使用 svelte+rollup+rollup-plugin-polyfill

SCRIPT438:对象不支持“最近”的属性或方法

即使我包含了仍然会发生

polyfill(['@webcomponents/webcomponentsjs','element-closest']),

在我的 rollup.js 中。

调用发生在这段代码中:

function onDocumentClick (e) {
    if (!e.target.closest('.autocomplete')) close();
}

为什么 polyfill 不存在?但是,如何正确使用它?我正在考虑用一个 IE11 支持替换 .closest。

【问题讨论】:

  • DOM 遍历的.closest() 方法与 Web 组件无关,这就是为什么它不太可能在任何 Web 组件 polyfill 套件中找到。但是,您可以很容易地手动填充它,例如使用 MDN 提供的方法之一:developer.mozilla.org/en-US/docs/Web/API/Element/…

标签: javascript internet-explorer svelte rollupjs


【解决方案1】:

使用 Polyfill

if (!Element.prototype.matches) {
  Element.prototype.matches = Element.prototype.msMatchesSelector || 
                              Element.prototype.webkitMatchesSelector;
}

if (!Element.prototype.closest) {
  Element.prototype.closest = function(s) {
    var el = this;

    do {
      if (Element.prototype.matches.call(el, s)) return el;
      el = el.parentElement || el.parentNode;
    } while (el !== null && el.nodeType === 1);
    return null;
  };
}

Closest in detail and Polyfill

【讨论】:

  • do { 上遇到Invalid calling object 错误——有什么想法吗?
猜你喜欢
  • 2016-12-15
  • 2021-10-09
  • 1970-01-01
  • 1970-01-01
  • 2020-12-25
  • 2016-10-22
  • 1970-01-01
  • 2019-07-02
  • 2017-07-23
相关资源
最近更新 更多