如果您需要在<>虚拟空间环境中(如J.DOM)进行测试,你可能无法检索正确的特殊空间单元类型或名称空间。
In this case you may check whether an element is wrapped in an SVG via closest()
method (it also returns true if the current element is a SVG).
console.log(isSVGEl(svg))
console.log(isSVGEl(foreignObject))
console.log(isSVGEl(aHtml))
console.log(isSVGEl(aSvg))
console.log(isSVGEl(filter))
console.log(isSVGEl(svgInForeign))
function isSVGEl(el) {
let inSVG = el.closest( svg ) ? true : false
let inForeignObject = el.closest( foreignObject ) ? true : false
let isSVGElement = inSVG && inForeignObject ? (el.nodeName === el.nodeName.toLowerCase() ? true : false) : true
let data = {
nodeName: el.nodeName,
inSVG: inSVG,
inForeignObject: inForeignObject,
isSVGElement: isSVGElement
}
console.log(data)
return inSVG
}
<svg id="svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 100 100">
<filter id="filter">
<feGaussianBlur stdDeviation="5" />
</filter>
<g id="g">
<rect id="rect" width="100%" height="100%" x="0" y="0" fill="#ccc" />
<a id="aSvg" href="https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject">
<text id="text" x="50%" y="50%" font-size="10%" fill="blue">Svg link</text></a>
</g>
<!-- Common use case: embed HTML text into SVG -->
<foreignObject id="foreignObject" x="0" y="0" width="50" height="50">
<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:5px">
foreignObject:
<a id="aHtml" href="#">HTML link</a>
<svg id="svgInForeign" xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
viewBox="0 0 100 100">
</svg>
</div>
</foreignObject>
</svg>
Obviously, this requires your virtual DOM parser to support closest()
.
The above example also checks HTML elements within a ´`. In this case you need to my include additional data for you needs: e.g if element is wrapped in a foreignObject (so part of an SVG) but essentially a HTML element.