此HTML文件有一个脚本标记,可以在div like this中创建彩色div广场,但JavaScript没有显示在onload上。
<!DOCTYPE html>
<html>
<head>
<title>An Example Project</title>
<meta http-equiv="refresh" content="3">
<style>
div {position:absolute}
</style>
</head>
<body id="theBody" onload="show_pattern()">
<script>
function show_pattern() {
var top_position = 25, left_position = 25; // set up variables
var width = 500, height = 500;
var color_list = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"];
var the_body = document.getElementById("theBody"); //add div node to body
while (width > 50) {
var this_div = document.createElement("div");
var random_color = Math.random() * 7; //0-6.999
random_color = Math.floor(random_color); // 0-6 (7 total from list)
this_div.style.top = top_position + "px";
this_div.style.left = left_position + "px";
this_div.width = width + "px";
this_div.style.height = height + "px";
this_div.style.background = color_list[random_color];
the_body.appendChild(this_div);
top_position += 10;
left_position += 10;
width -= 20;
height -= 20;
}
}
</script>
</body>
</html>
答案 0 :(得分:0)
代码可能有逻辑错误。除此之外,它工作得很好:http://jsfiddle.net/usLv6rzh/
<body id="theBody" onload="show_pattern()">
<script>
function show_pattern() {
var top_position = 25, left_position = 25; // set up variables
var width = 500, height = 500;
var color_list = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"];
var the_body = document.getElementById("theBody"); //add div node to body
while (width > 50) {
var this_div = document.createElement("div");
var random_color = Math.random() * 7; //0-6.999
random_color = Math.floor(random_color); // 0-6 (7 total from list)
this_div.style.top = top_position + "px";
this_div.style.left = left_position + "px";
this_div.width = width + "px";
this_div.style.height = height + "px";
this_div.style.background = color_list[random_color];
the_body.appendChild(this_div);
top_position += 10;
left_position += 10;
width -= 20;
height -= 20;
}
}
</script>
答案 1 :(得分:0)
您没有正确设置宽度。它应该是
this_div.style.width = width + "px";