首页 > 解决方案 > 在 Internet Explorer 中查找父“SVG”元素

问题描述

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),但没有成功。

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

标签: javascriptinternet-explorersvginternet-explorer-11

解决方案


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

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

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


推荐阅读