开发者问题收集

使用 javascript 修改 grid-template-columns

2019-05-30
6858

我试图在单击按钮时更改 grid-template-columns 的大小( https://jsfiddle.net/3ft6svgk/2/ )。

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;
}

javscript:

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 的值?

2个回答

尝试一下:

firstButton = document.getElementById("firstButton")
firstButton.onclick = function(){
  squaresGrid = document.getElementsByClassName("grid-squares");
  squaresGrid[0].style.gridTemplateColumns = "1000px";
}
Ghoul Ahmed
2019-05-30

.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";

您还需要使用 非侵入式 JavaScript ,并 向您的按钮添加事件监听器 ,而不是使用 .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>
Obsidian Age
2019-05-30