我当前的代码创建了一个网格,其中span元素的类名为gridsquare。我试图弄清楚如何将样式应用于所有这些。我一直收到错误TypeError:size.style未定义。我将函数设置为在创建元素后运行,不确定发生了什么......
let n=16;
let boxSize = 720/n;
function grid(){
for(var i = 1; i < n; i++) {
document.getElementById('container').innerHTML+='<div class="row">'
for(k = 0; k < n; k++) {
document.getElementById('container').innerHTML+='<span class="gridsquare">as</span>';
}
}
gridSize()
}
function gridSize(){
let size = document.getElementsByClassName("gridsquare")
size.style.height = boxSize;
size.style.width = boxSize;
}
grid()
答案 0 :(得分:0)
这会让你尝试使用像
一样的数组function gridSize(){
let size = document.getElementsByClassName("gridsquare")
size[0].style.height = boxSize;
size[0].style.width = boxSize;
}
答案 1 :(得分:0)
使用getElementsByClassName
时必须使用索引,因为getElementsByClassName
会返回节点集合。
size[0].style.width = boxSize;
size[0].style.width = boxSize;
工作代码段:使用querySelectorAll()
let n=16;
let boxSize = 720/n;
function grid(){
for(var i = 1; i < n; i++) {
document.getElementById('container').innerHTML+='<div class="row">'
for(k = 0; k < n; k++) {
document.getElementById('container').innerHTML+='<span class="gridsquare">as</span>';
}
}
gridSize();
}
function gridSize(){
let boxSize = '20px';
let size = document.querySelectorAll(".gridsquare");
size.forEach(function(spanEl){
spanEl.style.height = boxSize;
spanEl.style.width = boxSize;
spanEl.style.display = 'inline-block';
});
}
grid();
<div id="container"></div>
OR:如果您想使用getElementsByClassName()
let n=16;
let boxSize = 720/n;
function grid(){
for(var i = 1; i < n; i++) {
document.getElementById('container').innerHTML+='<div class="row">'
for(k = 0; k < n; k++) {
document.getElementById('container').innerHTML+='<span class="gridsquare">as</span>';
}
}
gridSize();
}
function gridSize(){
let boxSize = '20px';
let size = document.getElementsByClassName("gridsquare");
[].forEach.call(size, function(spanEl){
spanEl.style.height = boxSize;
spanEl.style.width = boxSize;
spanEl.style.display = 'inline-block';
});
}
grid();
<div id="container"></div>