【问题标题】:Find parent "SVG" element in Internet Explorer在 Internet Explorer 中查找父“SVG”元素
【发布时间】:2021-02-13 03:53:53
【问题描述】:

var HELPERS = {
  getElem: function($this) {
    return HELPERS.findAncestor($this, "svg");
  },
  findAncestor: function (el, sel) {
    while ((el = el.parentElement) && !((el.matches || el.matchesSelector).call(el,sel)));
    console.log(!el ? "Not found" : "Found");
    return el;
  },
 }
<div>
  <svg height="150" width="500">
    <ellipse onclick="HELPERS.getElem(this)" cx="240" cy="100" rx="220" ry="30" style="fill:purple" />
    <ellipse onclick="HELPERS.getElem(this)" cx="220" cy="70" rx="190" ry="20" style="fill:lime" />
    <ellipse onclick="HELPERS.getElem(this)" cx="210" cy="45" rx="170" ry="15" style="fill:yellow" />
    Sorry, your browser does not support inline SVG. 
  </svg>
</div>

如您所见,这适用于现代浏览器,不幸的是我需要 IE11 支持。我尝试了不同的 findAncestor 功能(例如使用 .closest polyfill),但没有成功。

任何可以帮助我解决这个问题的东西都将不胜感激。

【问题讨论】:

  • 你有一个问题要解决,你不能完全弄清楚按原样编写的代码。我是否可以建议您重构 while 循环,使其不那么抽象和具有神秘副作用的魔力?那么问题可能对您来说很明显或更容易解决。
  • parentNode 而不是 IE 的 parentElement 我认为。
  • 谢谢大家。越来越近了,是的,parentElement 是问题的一部分。现在我需要为 IE 中的 svg 找到 matches || matchesSelector 的替代方案。
  • 考虑阅读the mdn article。它甚至包含如何为不支持的浏览器填充方法。 --- 文章说 IE11 支持matches...
  • 谢谢大家,现在似乎可以工作了

标签: javascript internet-explorer svg internet-explorer-11


【解决方案1】:

所有 SVG DOM 元素都有一个名为 ownerSVGElement 的属性。它指向最近的祖先&lt;svg&gt; 元素。我已经检查过 IE11 也支持这一点。所以以下应该可以工作。

var HELPERS = {
  getElem: function($this) {
    return $this.ownerSVGElement;
  }
}

当然,这假设您在代码中的其他地方不需要 findAncestor() 方法。

【讨论】:

    【解决方案2】:

    cmets的累积,我想出了这个解决方案。

    1. 如果parentElement 不存在,请使用parentNode
    2. 添加.matches polyfill
    (import .matches polyfill here)
    
    var HELPERS = {
      getElem: function($this) {
        return HELPERS.findAncestor($this, "svg");
      },
      findAncestor: function (el, sel) {
        if (typeof el.closest === "function") {
          return el.closest(sel) || null;
        }
        while ((el = el.parentElement || el.parentNode) && !((el.matches || el.matchesSelector).call(el,sel)));
        return el;
      },
     }
    

    .matchespolyfill:https://developer.mozilla.org/en-US/docs/Web/API/Element/matches#Polyfill

    【讨论】:

    • 感谢您发布此问题的解决方案。我建议你尝试在 48 小时后标记你自己对这个问题的答案,当它可以标记时。它可以在未来帮助其他社区成员解决类似的问题。感谢您的理解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-31
    • 2016-03-21
    • 1970-01-01
    相关资源
    最近更新 更多