![](/img/trans.png)
[英]Can I change the width and height of a div using javascript scroll event?
[英]Why can't I add width and height to my div using javascript on 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);
}
}());
問題是divs似乎沒有采用我給他們的寬度。
這也是我嘗試執行的方法之一,我很確定這不是最好的方法,如果你們有辦法實現相同目標,但是請以優雅的方式分享
首先: div
是塊級元素,因此默認情況下它將覆蓋整個元素。 第二:設置寬度/高度樣式后,您在square.setAttribute('style','border:2px solid black');
覆蓋了它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);
}
}());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.