0

当在 HTML 页面上单击提交按钮时,一个框也应显示在页面上任何颜色的任何位置。我正在使用外部 JavaScript 页面来完成此操作。但是,它不起作用...我尝试对其进行调试,但它不会超过var body = document.getElementsById("body")[0];

这是HTML代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Exercise 2 - Question 2</title>
        <script src="E02_Q2.js"></script>
    </head>

    <body>
        <form> 
            <input type="submit" value="Add Box" onclick="ShowBox()"/>
        </form>
    </body>

</html>

这是伴随它的外部Javascript:

function ShowBox(){
    //get the body element of the document
    var body = document.getElementsById("body")[0];

    //create the canvas tag
    var canvas = document.createElement("canvas");
    canvas.height = 200;
    canvas.width = 200;
    var context = canvas.getContext("2d");

    //create the box and append onto the canvas 
    canvas.fillStyle = "#FF0000";
    canvas.fillRect(50,50,100,100); 

    //append the canvas onto the body 
    body.appendChild(canvas);
}

不太确定我在哪里出错了......

4

2 回答 2

2

首先,下面一行有错误。(你没有任何带有idas的元素body,即使有一个带有id='body'方法 is not的元素getElementsById,它也应该是getElementById。)

var body = document.getElementsById("body")[0];

相反,它应该像下面使用getElementsByTagName

var body = document.getElementsByTagName("body")[0];

、应开fillStyle与不开。fillRectcontextcanvas

context.fillStyle = "#FF0000";
context.fillRect(50,50,100,100); 

第三,您必须return false;阻止submit按钮的默认操作,如下所示:

<input type="submit" value="Add Box" onclick="ShowBox();return false;"/>

小提琴

于 2013-09-21T01:46:41.237 回答
1

将表单按钮更改为普通按钮。否则在函数中添加 return false 。

<form> 
        <input type="button" value="Add Box" onclick="ShowBox()"/>
</form>

该函数还有更多错误。请检查下面的脚本。

例如:http: //jsfiddle.net/3EwxB/

function ShowBox(){

     var body = document.getElementsByTagName("body")[0];

    //create the canvas tag
    var canvas = document.createElement("canvas");
    canvas.height = 200;
    canvas.width = 200;
    var context = canvas.getContext("2d");

    //create the box and append onto the canvas 
    context.fillStyle = "#FF0000";
    context.fillRect(50,50,100,100); 

    //append the canvas onto the body 
    body.appendChild(canvas);

}
于 2013-09-21T01:48:54.307 回答