如何在JavaScript代码中实现HTML元素?

3

我正在尝试设计一个样例网页,但在使用svg时遇到了一些问题...

我创建了一个带有线条的svg圆形,并且这个线条会随着圆形的旋转而移动。以下是示例代码:

<?xml version="1.0" encoding="iso-8859-1"?>

<svg width="100%" height="100%">
<circle cx="200" cy="200" r="100" stroke="black" stroke-width="4" fill="black" />
<g transform="translate(200,200)">
<line x1="0" y1="0" x2="100" y2="0" style="stroke:rgb(255,255,255);stroke-width:2">
<animateTransform attributeName="transform"
                        attributeType="XML"
                        type="rotate"
                        from="25" to="360" dur="100s"/>
</line>
</svg>

在上面的示例代码中,'line'会在页面启动后立即开始旋转,但我希望在按下“开始”按钮后才旋转,类似于这样...
<input type="button" value=" START " onclick="start()" class="control-menu-top-btn" id="green-btn">

<script language="javascript" type="text/javascript">
function start()
{
  .. ?
}
</script>

不太明白您的意思。您是想在JS中创建一个HTML元素,并将其插入到HTML代码中吗? - aSoler
1个回答

3

beginElement 方法将启动动画。在标记中将begin属性设置为indefinite会使动画在javascript启动之前停止运行。

html, body {
  width: 100%;
  height: 100%;
}
<input type="button" value=" START " onclick="start()" class="control-menu-top-btn" id="green-btn">

<script>
function start()
{
  document.getElementById("transform").beginElement();
}
</script>
<svg width="100%" height="100%">
<circle cx="200" cy="200" r="100" stroke="black" stroke-width="4" fill="black" />
<g transform="translate(200,200)">
<line x1="0" y1="0" x2="100" y2="0" style="stroke:rgb(255,255,255);stroke-width:2">
<animateTransform id="transform" attributeName="transform"
                        attributeType="XML"
                        type="rotate"
                        from="25" to="360" dur="100s" begin="indefinite" />
</line>
</g>
</svg>


谢谢...如果可能的话,你能告诉我如何在函数start()内更改animateTransform的'from'或'to'属性吗? - Legolas
setAttribute就像任何其他属性一样。 - Robert Longson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接