javascript 如何使用javascript设置div标签的高度和宽度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15496316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set div tag height and width using javascript?
提问by Shiju K Babu
How can I set the width and height of a div
using JavaScript?
如何div
使用 JavaScript设置宽度和高度?
Here is my code
这是我的代码
<%@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>
I want to set the div width to maxx
and height to maxy
values. I also want to set its border to 1px
so that I can see whether it's working or not.
我想将 div 宽度设置maxx
为maxy
值,将高度设置为值。我还想将其边框设置为1px
以便我可以查看它是否正常工作。
Thanks
谢谢
回答by SteveP
You need to use
你需要使用
document.getElementById('set').style.width = maxX + "px";
and
和
document.getElementById('set').style.height = maxY + "px";
Also, you may need to make sure the document is loaded before the script runs, or else the set div may not have been created. You do this in window.onload as foillows:
此外,您可能需要确保在脚本运行之前加载文档,否则可能尚未创建设置的 div。您可以在 window.onload 中按照以下方式执行此操作:
window.onload = function ()
{
Javascript code goes here
}
回答by James Donnelly
You'd make use of the element's style
:
你会利用元素的style
:
document.getElementById('set').style.width = maxx + "px";
document.getElementById('set').style.height = maxy + "px";
document.getElementById('set').style.border = "1px solid #000";
Being a fixed value, border in this case would probably be better controlled with just CSS.
作为一个固定值,这种情况下的边框可能会更好地用 CSS 控制。
div#set {
border:1px solid #000;
}