更改点击事件的网格布局

时间:2019-04-18 05:48:05

标签: javascript html css css3 css-grid

是否可以在单击事件上更改网格布局?我有一个显示三行的网格,我希望当单击该行中的项目时将网格更改为三列。

.gridcontainer {
  display: grid;
  grid-template-rows: 1fr 1fr 1fr;
  justify-content: center;
}

.gridcontainer {
  display: grid;
  grid-template-columns: 1fr 4fr 1fr;
  justify-content: center;
}
<div class="gridcontainer">
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
</div>

在任何一项的单击事件上,我希望网格显示从三行更改为三列。

3 个答案:

答案 0 :(得分:2)

设置两个单独的类:

.row {
  grid-template-rows: 1fr 1fr 1fr;
}

.col {
  grid-template-columns: 1fr 4fr 1fr;
}

每次点击都切换.gridcontainer上的每个班级。演示中有详细评论。

// Reference the .gridcontainer
var grid = document.querySelector('.gridcontainer');

// Register click event to grid callback rowCol runs on click
grid.onclick = rowCol;

/* 
Callback function rowCol() passes the Event Object...
if the clicked element (e.target) .matches() class .item...
get the clicked element's (ie .item) .closest() element .gridcontainer and 
add/remove class .col or .row
*/
function rowCol(e) {
  if (e.target.matches('.item')) {
    e.target.closest('.gridcontainer').classList.toggle('row');
    e.target.closest('.gridcontainer').classList.toggle('col');
  }
  return false;
}
.gridcontainer {
  display: grid;
  justify-content: center;
}

.row {
  grid-template-rows: 1fr 1fr 1fr;
}

.col {
  grid-template-columns: 1fr 4fr 1fr;
}
<div class="gridcontainer row">
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
</div>

答案 1 :(得分:0)

如果您询问事件的外观,您会看到以下内容:

$( "#grid" ).on( "click", function() {
  $( this ).css( "grid-template-columns", "1fr 4fr 1fr" );
});

,您可以看看这个answer

答案 2 :(得分:0)

您云尝试使用这种纯js

let gridContainer = document.querySelector('.gridContainer')
gridContainer.addEventListener("click", function(){
gridContainer.classList.toggle("style_for_row"); // if active its put to off
gridContainer.classList.toggle("style_for_colomn");// and if off put to on
});  //so on every click your changing the className

在CSS中,您可以有两个类

style_for_row{grid-template-rows: 1fr 1fr 1fr;}
style_for_column{grid-template-columns: 1fr 1fr 1fr;}
.gridcontainer {
 display: grid;
 justify-content: center;}

和html就像

<div class="gridcontainer style_for_column">
    <div class="item">Item</div>
    <div class="item">Item</div>
    <div class="item">Item</div>
    <div class="item">Item</div>
    <div class="item">Item</div>
    <div class="item">Item</div></div>