所以我正在玩一些有人要求我做的挑战:在彼此内部绘制正方形,但内部正方形的边必须是直接外部正方形的一半,并且它们必须居中
这是我到目前为止写的代码:
(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
是一个 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/