当在 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];
Second、fillStyle
和 fillRect
应该位于 context
上,而不是 canvas
.
context.fillStyle = "#FF0000";
context.fillRect(50,50,100,100);
第三,您必须return false;
以防止submit
按钮的默认操作,如下所示:
<input type="submit" value="Add Box" onclick="ShowBox();return false;"/>
关于javascript - 使用外部 Javascript 在 HTML 页面上显示一个框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18928046/