2011-07-23 61 views
1

我在通过javascript操纵SVG时遇到了一些麻烦。我想通过点击一个按钮来增加一行的长度。我已经包括在头标记此代码:脚本编写SVG时出现问题

<script type="text/javascript"> 
x=135; 
y=135; 
var container = document.getElementById("svgbox"); 
var mySvg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); 


function svg() { 
mySvg.setAttribute("version", "1.2"); 
mySvg.setAttribute("baseProfile", "tiny"); 
mySvg.setAttribute("height","300px"); 
mySvg.setAttribute("width","300px"); 
container.appendChild(mySvg); 
} 

function line() { 
x=x-10; 
y=y-10; 
var L1 = document.createElementNS("http://www.w3.org/2000/svg", "line"); 
    L1.setAttribute("x1", "100"); L1.setAttribute("y1", "100"); 
    L1.setAttribute("x2", x); L1.setAttribute("y2", y); 
    L1.setAttribute("stroke", "#05adc7"); 
    L1.setAttribute("stroke-width", "2px"); 
    mySvg.appendChild(L1); 
} 
</script> 

这是正文:

<body onload="svg()"> 
<form> 
<input type="button" onClick="line()" /> 
</form> 
<div id="svgbox"> 
</div> 
</body> 

但是当我按一下按钮,我得到一个错误,告诉我变量“容器“ 一片空白。有谁知道问题是什么?

回答

1

它的作品,如果你把行var container = document.getElementById("svgbox");在svg函数。

function svg() { 
var container = document.getElementById("svgbox"); 
mySvg.setAttribute("version", "1.2"); 
mySvg.setAttribute("baseProfile", "tiny"); 
mySvg.setAttribute("height","300px"); 
mySvg.setAttribute("width","300px"); 
container.appendChild(mySvg); 
} 

原因容器是在你的代码null是因为当行var container = document.getElementById("svgbox");被执行的DOM尚未加载。

您需要在DOMContentLoaded事件或window.onload事件触发后声明容器。

+0

这有效。谢谢您的帮助。 – dopatraman

1

这是一个常见的DOM脚本编写的问题,对于SVG和HTML都是如此。问题在于,当JavaScript执行时,svgbox元素尚未加载。最简单的解决方案是简单地移动脚本标签,使其成为文档中的最后一个元素。然而,这有点难看,因此大多数JavaScript库都包含一个接受回调以在文档加载后执行的方法。例如,如果您使用的是jQuery,那么您的脚本标签看起来将如下所示:

<script type="text/javascript"> 
$(document).ready(function(){ 
    x=135; 
    y=135; 
    var container = document.getElementById("svgbox"); 
    var mySvg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); 


    svg = function() { 
    mySvg.setAttribute("version", "1.2"); 
    mySvg.setAttribute("baseProfile", "tiny"); 
    mySvg.setAttribute("height","300px"); 
    mySvg.setAttribute("width","300px"); 
    container.appendChild(mySvg); 
    } 

    line = function() { 
    x=x-10; 
    y=y-10; 
    var L1 = document.createElementNS("http://www.w3.org/2000/svg", "line"); 
    L1.setAttribute("x1", "100"); L1.setAttribute("y1", "100"); 
    L1.setAttribute("x2", x); L1.setAttribute("y2", y); 
    L1.setAttribute("stroke", "#05adc7"); 
    L1.setAttribute("stroke-width", "2px"); 
    mySvg.appendChild(L1); 
    } 
}) 
</script> 
+0

原来,最简单的方法是将容器包含在线路功能中。感谢您的回应。 – dopatraman

+0

另一个快速问题....我认为我可以通过在head标签内激发onload事件来解决代码美学和功能性问题。但这不起作用。有谁知道为什么? – dopatraman

+0

你的意思是“在头标签中发生onload事件”? – jbeard4