javascript - 为什么我不能在 html dom 上使用 javascript 将宽度和高度添加到我的 div

标签 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.width =width+'px';
        square.style.height =width+'px';
        square.setAttribute('style','border:2px solid black');
        width=width/2;
        bodyEle.appendChild(square);

    }
}());

问题是 div 似乎没有采用我给它们的宽度。

这也是我尝试这样做的一种方式,我很确定这不是最好的方式,如果你们有办法实现相同但以优雅的方式请分享

https://jsfiddle.net/op22uLug/3/

最佳答案

首先:div是一个 block 级元素,所以默认会跨越full with。 第二:设置宽度/高度样式后,您在 square.setAttribute('style','border:2px solid black');

中覆盖了它

正确的代码是:

(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);
  }
}());

关于javascript - 为什么我不能在 html dom 上使用 javascript 将宽度和高度添加到我的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33727691/

相关文章:

jQuery 对话框未捕获控件 - IE 9.0

javascript - 事件参数及其用途

javascript - D3.js如何获取transform attr的值

javascript - 函数调用时防止默认值

javascript - 为什么 jQuery 在 HTML 中插入 value 属性,而 document.getElementById(...).value 却没有?有解决方法吗?

jquery - 以 HTML 格式生成 PDF 文件的缩略图

javascript - 在按钮中添加下划线幻灯片过渡

jQuery - 不使用图像滑动背景颜色

javascript - 如何延迟fb api中的api调用

javascript - 动态创建的元素上的 addEventListener 不起作用