【发布时间】:2012-07-30 21:25:49
【问题描述】:
我有这个 HTML 代码,它正在调用我的 javascript 代码。该代码用于量规。在 javascript 代码中,我试图访问一个 SVG 文件,并修改指针(仪表的)以显示所需的值。代码工作正常。但是,我不想在 HTML 中调用“object id”。我想直接通过 javascript 访问 SVG 文件,而不是在 HTML 中使用对象 id。我尝试使用 el.setAttribute('data', 'gauge.svg');但随后 svg_doc 无法检索 SVG 图像并修改针。任何帮助将不胜感激。
PS:我尽我最大的努力来解释这个问题。但是,如果我在某处不清楚,请告诉我。
这是 Gauge.png 图像,它嵌入在我粘贴在 https://sphotos-b.xx.fbcdn.net/hphotos-snc6/179594_10150982737360698_1827200234_n.jpg 下方的 svg 代码中
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g name="gauge" width="122px" height="127px">
<image xlink:href="gauging.png" width="122" height="127"/>
<circle id="led" cx="39" cy="76" r="5" style="fill: #999; stroke: none">
<animateColor id="ledAnimation" attributeName="fill" attributeType="css" begin="0s" dur="1s"
values="none;#f88;#f00;#f88;none;" repeatCount="0"/>
</circle>
<g id="needle" transform="rotate(0,62,62)">
<circle cx="62" cy="62" r="4" style="fill: #c00; stroke: none"/>
<rect transform="rotate(-130,62,62)" name="arrow" x="58" y="38" width="8" height="24" style="fill: #c00; stroke: none"/>
<polygon transform="rotate(-130,62,62)" points="58,39,66,39,62,30,58,39" style="fill: #c00; stroke: none"/>
</g>
<text id="value" x="51" y="98" focusable="false" editable="no" style="stroke:none; fill:#fff; font-family: monospace; font-size: 12px"></text>
</g>
</svg>
HTML+Javascript 代码
<head>
<title>SVG Gauge example</title>
<script>
function update1(){
var scale=100;
var value;
var value1 = 69;
var el=document.getElementById('gauge1');
if (!el) return;
/* Get SVG document from HTML element */
var svg_doc = el.contentDocument;
if (!svg_doc) return;
/* Rotate needle to display given value */
var needle_el = svg_doc.getElementById('needle');
if (!needle_el) return;
/* Calc rotation angle (0->0%, 260->100%) */
value = parseInt(value1);
scale = parseInt(scale);
if (value > scale) value = scale;
var angle = value / scale * 260;
/* On-the-fly SVG transform */
needle_el.setAttribute('transform','rotate('+angle+',62,62)');
}
document.addEventListener('load', update1, true);
</script>
</head>
<div>
<object id="gauge1" type="image/svg+xml" data="gauge.svg" width="127" height="122"/>
</div>
</html>
【问题讨论】:
-
我不太确定你为什么对当前的方法如此生气,这就是你的做法。我不知道您所说的“对象ID”是什么意思?如果您不希望涉及任何 HTML,请将 JS 直接放入 SVG。
-
如果您查看 html 代码,您会看到我使用“gauge1”作为对象 id,它指的是我的主图像“gauge.svg”。没有什么比得罪我的了,我可以详细解释一下在我的项目中使用 html 中的对象 ID 引用的含义。无论如何,对于解决我的问题的任何反馈将不胜感激。
-
这不是问题,它应该是这样工作的,没有什么可以“解决”的。如果您有一些特殊要求意味着您不能这样做,那么您最好在问题中说明这些要求。
-
好的。我的要求是我只想使用 Javascript 访问 SVG 文件。我将完全删除 HTML。是否可以访问和修改 SVG 文件,只使用 JS 进行上述代码。
标签: javascript html svg web