gpt4 book ai didi

javascript - 如何使用 document.evaluate 查询 svg 元素?

转载 作者:行者123 更新时间:2023-12-03 08:21:46 25 4
gpt4 key购买 nike

我有一个带有 div 元素的文档,其中包含 svg 元素。

当我查询 div 元素时,我得到一个返回值,甚至显示 svg 子元素。

$x('//div')
[<div class=​"schema">​…​</div>​, <div class=​"relations">​<svg class=​"relations">​…​</svg>​</div>​]

但是当我查询 svg 元素本身时,我没有得到任何结果。

$x('//svg')
[]

我不知道为什么。我在 Chromium 45.0.2454.85 中做到了这一点。

有人能解释一下这里发生了什么吗?

最佳答案

SVG 元素位于 SVG 命名空间 http://www.w3.org/2000/svg 中,如果您使用 evaluate DOM 方法,那么您可以通过在命名空间解析器中作为第三个参数:

function setFill(xpath, color) {
var el = document.evaluate(xpath, document, function(prefix) { if (prefix === 'svg') { return 'http://www.w3.org/2000/svg'; }}, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
if (el !== null) {
el.setAttribute('fill', color);
}
}
<div>
<svg width="200" height="200">
<circle cx="100" cy="100" r="50" fill="green"/>
</svg>
<input type="button" value="red" onclick="setFill('//svg:circle', 'red');">
</div>

我不知道开发者工具中的$x函数是否允许类似的功能。

关于javascript - 如何使用 document.evaluate 查询 svg 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33719073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com