如何使用javascript设置div标签的高度和宽度?

时间:2013-03-19 10:00:06

标签: javascript html jsp height width

如何使用JavaScript设置div的宽度和高度?

这是我的代码

<%@page import="org.json.JSONObject"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>View JSON</title>
<script type="text/javascript">
var rect1='{"minX": 0.0,"minY": 0.0,"maxX": 2460.0,"maxY": 3008.0}';
var rectangle = JSON.parse(rect1);
var maxx=rectangle.maxX;
var maxy=rectangle.maxY;

***What should i do here?***

</script>
</head>
<body>
<h5>JSON View</h5>
<div id="set">
</div>
</body>
</html>

我想将div宽度设置为maxx,将高度设置为maxy值。我还想将其边框设置为1px,以便我可以看到它是否正常工作。

由于

2 个答案:

答案 0 :(得分:6)

您需要使用

document.getElementById('set').style.width = maxX + "px";

document.getElementById('set').style.height = maxY + "px";

此外,您可能需要确保在脚本运行之前加载文档,否则可能尚未创建set div。你在window.onload中以foillows:

执行此操作
window.onload = function ()
{
  Javascript code goes here
} 

答案 1 :(得分:3)

您将使用元素style

document.getElementById('set').style.width = maxx + "px";
document.getElementById('set').style.height = maxy + "px";
document.getElementById('set').style.border = "1px solid #000";

JSFiddle example

作为一个固定值,在这种情况下,边框可能更好地用CSS控制。

div#set {
    border:1px solid #000;
}
相关问题