我正在制作的页面旨在:
- 取一组瓷砖和一堵墙的尺寸,然后打印出需要多少瓷砖才能填满墙的面积
- 在屏幕上打印出墙上贴有瓷砖的视觉效果。
到目前为止,我已经成功完成了第一部分。
<style>
#wallspace {
width:300px;
height:auto;
overflow:hidden;
position:relative;
margin:auto;
}
</style>
<form >
Tile Dimensions<br />
Width: <input type="text" id="tile_width" />cm
height: <input type="text" id="tile_height" />cm
<br />
Wall Dimensions<br />
Width: <input type="text" id="wall_width" />cm
height:<input type="text" id="wall_height" />cm
</form>
<button onclick="createWall()" >Try it</button>
<p id="result"> </p>
<div id="wallspace">
</div>
<script language="javascript" type="text/javascript">
function createWall() {
//collect dimensions from user input
var tileWidth = document.getElementById("tile_width").value;
var tileHeight = document.getElementById("tile_height").value;
var wallWidth = document.getElementById("wall_width").value;
var wallHeight = document.getElementById("wall_height").value;
//find the areas of the tile and the wall
var tileArea = tileWidth * tileHeight;
var wallArea = wallWidth * wallHeight;
//divide these to find the number of tiles needed
var noOfTiles = (wallArea/tileArea);
document.getElementById("result").innerHTML="number of tiles needed are " +
noOfTiles;
}
</script>
现在在打印墙壁时,我试图使用嵌套的 for 循环来打印瓷砖。如下:
function printTiles()
{
var tileWidth = document.getElementById("tile_width").value;
var tileHeight = document.getElementById("tile_height").value;
var wallWidth = document.getElementById("wall_width").value;
var wallHeight = document.getElementById("wall_height").value;
//rows
for (var i = 0; i < wallHeight; i = i + tileHeight)
{
//collumns
for (var a = 0; a < wallWidth; a = a + tileWidth)
{
var div = document.createElement("div");
div.style.width = tileWidth + "px";
div.style.height = tileHeight + "px";
div.style.cssFloat = "left";
div.style.borderWidth = "2px";
div.style.borderStyle = "solid";
div.innerHTML = i;
document.getElementById("wallspace").appendChild(div);
}
}
因此嵌套的 for 循环将打印行上的每一列,而不是转到下一行,依此类推。出于某种原因,我的 printTiles 根本不工作,我不明白为什么?其次,当我让它工作时,我可以简单地使用
document.getElementById("wallspace").innerHTML=printTiles();
如果您不明白我要做什么,请发表评论,我会尝试更好地解释它。