更改点击事件的网格布局
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了更改点击事件的网格布局相关的知识,希望对你有一定的参考价值。
是否可以更改点击事件的网格布局?我有一个三行的网格显示,我希望在单击行中的项目时将网格更改为三列。
.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>
在任何项目上的单击事件上,我希望网格显示从三行更改为三列。
答案
制作两个单独的课程:
.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>
另一答案
如果您询问事件的外观,您可以看到:
$( "#grid" ).on( "click", function() {
$( this ).css( "grid-template-columns", "1fr 4fr 1fr" );
});
你可以看看这个answer
另一答案
你云试试这个纯粹的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>
以上是关于更改点击事件的网格布局的主要内容,如果未能解决你的问题,请参考以下文章