javascript - 在 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),但没有成功。
任何可以帮助我解决这个问题的东西都将不胜感激。
解决方案
所有 SVG DOM 元素都有一个名为ownerSVGElement
. 它指向最近的祖先<svg>
元素。我已经检查过 IE11 也支持这一点。所以以下应该工作。
var HELPERS = {
getElem: function($this) {
return $this.ownerSVGElement;
}
}
findAncestor()
当然,这假设您在代码中的其他地方不需要该方法。
推荐阅读
- docker - 在 DockerHub 上找不到图像
- python - 使用 Queue() 进行多处理:TypeError: can't pickle _thread.lock objects
- ios - 导航控制器未加载(推送、呈现)另一个视图控制器
- sql - 选择外键重复的值
- git - 如何检查我是否已经完成了 git commit --amend over some commit?
- timeline - 使用 vis 示例创建时间线
- inno-setup - 如何在单个 Inno Setup 安装程序中添加 x86 和 x64 VC++ 2019 Redistributables?
- python - Python 正则表达式从字符串中间删除特殊字符并忽略其他任何内容
- python - 如何将链表的最后一个元素移动到python中的第一个元素(下面的代码)?
- javascript - Divs被切断了?