【问题标题】:How to set div tag height and width using javascript?如何使用javascript设置div标签的高度和宽度?
【发布时间】:2013-03-07 22:33:39
【问题描述】:

如何使用 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,以便我可以查看它是否正常工作。

谢谢

【问题讨论】:

  • 从这样的字符串中将其解析为 JSON 有什么意义?为什么不直接创建一个对象字面量?无论如何,JSON 代表 javascript 对象表示法。此外,您还需要将该脚本放在 DOM 的底部,以确保首先解析和加载您希望操作的元素。
  • 简单地做document.getElementById("set").style.height = maxy+"px",同样宽度做document.getElementById("set").style.width = maxx+"px"。对于边框做document.getElementById("set").style.border = "solid 1px black"
  • 你可以在谷歌上找到这个问题,比你发布这个问题花费的时间还短:-)
  • @Gatekeeper 你认为我没有在谷歌搜索什么?
  • @Shiju K Babu 如果我将“set div width javascript”放入谷歌,前几页会告诉我如何做到这一点......

标签: javascript html jsp height width


【解决方案1】:

你会使用元素的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;
}

【讨论】:

    【解决方案2】:

    你需要使用

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

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

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

    window.onload = function ()
    {
      Javascript code goes here
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-26
      • 1970-01-01
      • 2013-01-15
      相关资源
      最近更新 更多