使用外部 Javascript 在 HTML 页面上显示一个框

Displaying a Box on an HTML page using external Javascript?

本文关键字:显示 一个 外部 Javascript HTML      更新时间:2023-09-26

当在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);
}

不太确定我在这里出了问题...

首先,下面一行有一个错误。(你没有任何元素id作为body,即使有一个元素id='body'方法不是getElementsById,它应该是getElementById的。

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

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

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

其次fillStylefillRect应该在context而不是canvas

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

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

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

小提琴

将表单按钮更改为普通按钮。否则在函数中添加返回 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);
}