function size(){
for(i=0; i<squares; i++){
document.getElementById('table').innerHTML += "<div class='squareCell' id='objetive"+i+"'></div>";
}
document.getElementsByClassName('squareCell').style.width="300px";
document.getElementsByClassName('squareCell').style.height="300px";}
仍在显示“无法设置未定义的属性'width'”,并且不知道为什么。我并不是想解决这个问题,我想了解一下这里到底发生了什么。
你好。
该getElementsByClassName()
方法以数组对象的形式返回文档中具有指定类名的所有元素的集合。
如果您有一个类名,squareCell
则可以通过定义第0个索引来做到这一点
document.getElementsByClassName('squareCell')[0].style.width="300px";
document.getElementsByClassName('squareCell')[0].style.height="300px";
如果您想使用多次使用循环
var x = document.getElementsByClassName('squareCell');
for(var i=0; i< x.length;i++){
x[i].style.width = "300px";
x[i].style.height = "300px";
}
或者
var elements = document.getElementsByClassName('squareCell');
Array.from(elements).forEach(function(element) {
element.style.height = '50px';
element.style.width = '50px';
});
function makeSquare(){
var elements = document.getElementsByClassName('squareCell');
Array.from(elements).forEach(function(element) {
element.style.height = '50px';
element.style.width = '50px';
});
}
.squareCell{
background-color: #ff00ff;
margin: 5px;
display: inline-flex;
align-items: center;
justify-content: center;
padding: 20px;
}
<button onclick="makeSquare()">Make Square</button>
<br/>
<div class="squareCell">Test1</div>
<div class="squareCell">Test2</div>
<div class="squareCell">Test3</div>
<div class="squareCell">Test4</div>
<div class="squareCell">Test5</div>
<div class="squareCell">Test6</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句