我正在尝试通过单击按钮(https://jsfiddle.net/3ft6svgk/2/)来更改grid-template-columns
的大小。
html:
<div class="grid-squares">
<div class="grid_item">
<h2>Lorem Ipsum</h2>
<button id="firstButton">Learn More</button>
</div>
<div class="grid_item">
<h2>Lorem Ipsum</h2>
</div>
<div class="grid_item">
<h2>Lorem Ipsum</h2>
</div>
<div class="grid_item">
<h2>Lorem Ipsum</h2>
</div>
</div>
css:
.grid-squares{
display: grid;
grid-template-columns: 1fr 1fr;
grid-auto-rows: 300px;
}
字幕:
firstButton = document.getElementById("firstButton")
firstButton.onclick = function(){
squaresGrid = document.getElementsByClassName("grid-squares");
squaresGrid.style.gridTemplateColumns = "1000px";
}
通过此代码,我得到
"Uncaught TypeError: Cannot set property 'gridTemplateColumns' of undefined
at HTMLButtonElement.repairsAndUpgradesButton.onclick"
在控制台中。如何正确更改grid-template-columns
的值?
答案 0 :(得分:1)
.getElementsByClassName()
返回元素的 NodeList 集合。
您要么需要遍历.gridSquares
:
squaresGrid = document.getElementsByClassName("grid-squares");
for (let i = 0; i < squaresGrid.length; i++) {
squaresGrid[i].style.gridTemplateColumns = "1000px";
}
或按索引访问它们(索引为0
时只有一个):
squaresGrid = document.getElementsByClassName("grid-squares")[0];
squaresGrid.style.gridTemplateColumns = "1000px";
您还希望在按钮上使用 Unobtrusive JavaScript 和 add an event listener 而不是使用.onclick
这可以在下面的工作示例中看到:
firstButton = document.getElementById("firstButton")
firstButton.addEventListener('click', function() {
squaresGrid = document.getElementsByClassName("grid-squares")[0];
squaresGrid.style.gridTemplateColumns = "1000px";
});
.grid-squares {
display: grid;
grid-template-columns: 1fr 1fr;
grid-auto-rows: 300px;
}
<div class="grid-squares">
<div class="grid_item">
<h2>Lorem Ipsum</h2>
<button id="firstButton">Learn More</button>
</div>
<div class="grid_item">
<h2>Lorem Ipsum</h2>
</div>
<div class="grid_item">
<h2>Lorem Ipsum</h2>
</div>
<div class="grid_item">
<h2>Lorem Ipsum</h2>
</div>
</div>
答案 1 :(得分:1)
尝试一下:
firstButton = document.getElementById("firstButton")
firstButton.onclick = function(){
squaresGrid = document.getElementsByClassName("grid-squares");
squaresGrid[0].style.gridTemplateColumns = "1000px";
}