【发布时间】: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