【问题标题】:How do I tell if a DOM element is HTML or SVG?如何判断 DOM 元素是 HTML 还是 SVG?
【发布时间】:2014-01-11 23:37:51
【问题描述】:

我正在编写一个需要以不同方式应用于 HTML 元素和 SVG 元素的基础架构。给定一个 DOM 节点,我如何判断它是 SVG 还是 HTML 元素?

【问题讨论】:

  • 不同意这个需要代码示例来说明问题,问题从文中就很清楚了。
  • @David 不仅关闭原因很荒谬,而且您会看到这个问题在 30 分钟内得到了对其他人有用的可靠答案。我不知道这些人在想什么。

标签: html dom svg


【解决方案1】:

您可以尝试以下方法:

if(document.getElementById("el") instanceof SVGElement) {
    console.log("It's an SVG element");
}
<svg xmlns="http://www.w3.org/2000/svg"
  xmlns:xlink="http://www.w3.org/1999/xlink" 
  width="300" height="300">
  <g id="firstGroup">
    <rect id="el" width="100" height="50" x="40" y="20" fill="blue" />
    <text x="40" y="100">This is a basic SVG document!</text>
  </g>
</svg>

请注意,&lt;svg&gt; 元素本身实际上是一个 HTML 元素包含 SVG 元素 - 这意味着,也许令人惊讶的是,&lt;svg&gt; HTML 元素 不是 一个SVG 元素,因此:

console.log(document.createElement("svg") instanceof SVGElement)) // => false

【讨论】:

  • 谢谢@BillCriswell,我想是的!
  • 我做了 if(element.getBBox){ 来检查元素是否有 getBBox 方法。某些函数/方法仅适用于 SVG 元素。
  • 这个答案是错误的。在 &lt;svg&gt; 上检查 instanceof SVGElement 将返回 true。您的演示返回 false 的原因是因为您需要使用 document.createElementNS 而不是 document.createElement 创建 svg 元素。因此,当使用instanceof SVGElement 进行检查时,它将返回true,而不是false。示例:console.log(document.createElementNS("http://www.w3.org/2000/svg","svg") instanceof SVGElement) // =&gt; true
【解决方案2】:

我不确定它的跨浏览器兼容性如何,但我正在浏览 DOM 属性并看到一个看起来很有希望的ownerSVGElement

这是我正在玩弄的东西:http://jsbin.com/uMIronal/4/edit?html,js,output

【讨论】:

  • 请注意,除非已将 SVG 元素添加到文档中,否则此方法不起作用 - 例如,document.createElementNS("http://www.w3.org/2000/svg", "circle").ownerSVGElement 将是 null,因此 instanceof 以这种方式更可靠和also performs better
猜你喜欢
  • 2010-09-25
  • 1970-01-01
  • 1970-01-01
  • 2015-02-11
  • 2014-07-18
  • 1970-01-01
  • 2012-08-10
  • 2018-07-05
  • 2010-09-12
相关资源
最近更新 更多