动态创建DIV,并不是动态地获取高度和宽度
Creating DIV dynamically, is not taking height and width on fly
我想根据一些计算动态创建div。我可以动态构建div,但唯一的问题是它不会占用fly的高度和宽度。如果可能的话,请任何人共享他们的视图或代码。
这是我用来给你参考的剧本。
<script type="text/javascript" language="javascript">
function createDiv()
{
var totalheight=400;
var totalwidth = 600;
var height = 80;
var width = 40;
var divheight = totalheight / height;
var divwidth = totalwidth / width;
var id=1;
for(var i=1;i<=divheight;i++)
{
var eh=divwidth;
var fh=1;
for (var w = 1; w <= divwidth; w++)
{
var div=document.createElement("<div id='"+id+"' style='"background:#F0E68C;width:'"+width+"'px;height:'"+height+"'px;border:solid 1px #c0c0c0;padding: 0.5em;text-align: center;float:left;'"></div>");
document.body.appendChild(div);
eh=eh+divheight;
fh=fh+divheight;
id++;
}
var div1=document.createElement("<br/>");
document.body.appendChild(div1);
}
}
</script>
提前谢谢。
试试这个。。希望这就是你想要做的。
<html>
<script type="text/javascript" >
function newDiv(){
var totalheight=400,ht = 80 , totalwidth = 600 ,wd = 40 ,i;
var divheight = totalheight / ht;
var divwidth = totalwidth / wd;
var id=1;
for(var i=1;i<=divheight;i++)
{
var eh=divwidth;
var fh=1;
for (i = 1; i <= divwidth; i++)
{
var div=document.createElement("div")
div.setAttribute("id","newDivId"+id)
div.setAttribute("class","newDiv")
div.style.width =wd+"px";
div.style.height =ht+"px";
document.body.appendChild(div);
eh=eh+divheight;
fh=fh+divheight;
id++;
}
var div1=document.createElement("<br/>");
document.body.appendChild(div1);
}
}
</script>
<style type="text/css">
.newDiv{
background-color:#F0E68C;
border:1px solid #c0c0c0;
padding: 0.5em;
text-align:center;
float:left;
}
</style>
<body>
<input type="button" onclick="newDiv()" value="Click Me">
</body>
</html>
看起来您没有向div添加任何内容,所以除非您有一些视觉样式(如border)在屏幕上看到它,否则您不会看到任何内容。
这里有几点需要注意
- 如果将高度和宽度设置为内联,则指定单位也例如
px
、em
等 - 添加一些视觉样式以使其显示在屏幕上
演示
相关文章:
- 使用JavaScript根据窗口/视口的高度动态调整图像大小
- javascript skrollr基于动态内容更新窗口高度
- window.open根据动态内容自动调整高度和宽度
- JQuery mCustomScrollbar动态高度
- 动态潜水高度jQuery.Load()不工作
- 在要更换的元件上取高度
- 动态iframe高度-似乎需要重新加载页面
- 具有动态块高度的类似Pinterest的插件
- 同位素布局中的动态iframe高度
- 自动调整动态更改高度(更小或更大)的 iframe
- 跨域中的动态 iframe 高度
- 使用格式化文本获取 DIV 或跨度的动态宽度高度
- 砌体/动态幻灯片高度问题
- jQuery抓取高度和运行函数仅用于此项
- 为Javascript附加的元素引导动态响应高度
- 我们在CSS/3中有什么东西可以根据宽度动态设置高度吗?
- 计算动态图像高度后如何执行JavaScript代码
- AngularJS用于动态改变高度的砌体
- AngularJS根据宽度动态更改高度
- 在CSS和JS中动态调整高度