javascript - 获取svg元素的位置

标签 javascript html svg

为什么我无法获取 cx 和 cy 的值? 它打印一些数组。我只需要 2 个值

<!DOCTYPE html>
<html>
<body>
<svg xmlns="http://www.w3.org/2000/svg">
    <circle cx="100" cy="100" r="50" fill="red" id="cir"/>
</svg>

<script>
        console.log(document.getElementById("cir").cx);
        console.log(document.getElementById("cir").cy);
</script>
</body>

</html>

最佳答案

cxcy 属性是 SVGAnimatedLength 对象,而不是字符串或数字。

要获取 cx 的实际值,您需要执行以下操作:

cx.baseVal.value

<!DOCTYPE html>
<html>
<body>
<svg xmlns="http://www.w3.org/2000/svg">
    <circle cx="100" cy="100" r="50" fill="red" id="cir"/>
</svg>

<script>
        console.log(document.getElementById("cir").cx.baseVal.value);
        console.log(document.getElementById("cir").cy.baseVal.value);
</script>
</body>

</html>

关于javascript - 获取svg元素的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47016584/

相关文章:

javascript - 在 JavaScript 代码中查找访问器方法 (node_modules)

javascript - 从 contentEditable div 中删除格式

html - 有没有办法编写屏幕阅读器会忽略的内容?

html - 可以将表单元素分组到 "p"中吗?

内联 SVG 上的 Jquery 切换类

javascript - AngularJS 架构尚未注册型号 'Post'

javascript - 将文本定位在网格中的 x、y 位置

javascript - 关闭主体点击事件上的工具提示 - 无法正常工作

jQuery SVG - 悬停元素

html - Bootstrap 导航栏品牌中的 SVG Logo