Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么可以';我在HTMLDOM上使用javascript向div添加宽度和高度_Javascript_Html_Css_Simple Html Dom - Fatal编程技术网

为什么可以';我在HTMLDOM上使用javascript向div添加宽度和高度

为什么可以';我在HTMLDOM上使用javascript向div添加宽度和高度,javascript,html,css,simple-html-dom,Javascript,Html,Css,Simple Html Dom,所以我在玩一个有人要求我做的挑战:在一个正方形内部画一个正方形,但是内部正方形必须有直接外部正方形的一半,并且必须居中 这是我到目前为止写的代码: (function(){ var width=200; var bodyEle=document.getElementById('result'); while(width>2){ var square =document.createElement('div'); square.style.w

所以我在玩一个有人要求我做的挑战:在一个正方形内部画一个正方形,但是内部正方形必须有直接外部正方形的一半,并且必须居中

这是我到目前为止写的代码:

(function(){
    var width=200;
    var bodyEle=document.getElementById('result');
    while(width>2){
    var square =document.createElement('div');

        square.style.width =width+'px';
        square.style.height =width+'px';
        square.setAttribute('style','border:2px solid black');
        width=width/2;
        bodyEle.appendChild(square);

    }
}());
问题是这些div看起来不像我给他们的宽度

这也是我尝试的方法之一,我很确定这不是最好的方法,如果你们有一种方法可以达到同样的效果,但要优雅的方式,请分享


首先:
div
是一个块级元素,因此默认情况下它将跨越完整的。 第二:设置宽度/高度样式后,您在
square.setAttribute('style','border:2px纯黑')中覆盖了它

正确的代码是:

(function(){
  var width=200;
  var bodyEle=document.getElementById('result');
  while(width>2){
    var square =document.createElement('div');

    square.style.width =width+'px';
    square.style.height =width+'px';
    square.style.display = 'inline-block';
    square.style.border = '2px solid black';
    //square.setAttribute('style','border:2px solid black');
    width=width/2;
    bodyEle.appendChild(square);
  }
}());

是的,它是有效的,泰,我也尝试中心是现在我有保证金0自动,但它似乎不工作,任何快速指针为什么这样。。
square.style.display='inline block'的用途是什么在那里?哦,这就像浮动,但在块上,我将其重置为显示块,它水平居中,但垂直方向仍在顶部:(垂直居中是完全不同的问题。您应该了解更多关于CSS布局的信息,和/或是的,我搜索了一些解决方案,其中一个是垂直对齐属性,但更通用的是使用相对位置和顶部,以%表示感谢您的回答:)