动态创建DIV,并不是动态地获取高度和宽度

Creating DIV dynamically, is not taking height and width on fly

本文关键字:动态 取高度 获取 创建 DIV 并不是      更新时间:2023-09-26

我想根据一些计算动态创建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)在屏幕上看到它,否则您不会看到任何内容。

这里有几点需要注意

  • 如果将高度和宽度设置为内联,则指定单位也例如pxem
  • 添加一些视觉样式以使其显示在屏幕上

演示