gpt4 book ai didi

javascript - 单击事件更改网格布局

转载 作者:行者123 更新时间:2023-11-30 11:05:39 25 4
gpt4 key购买 nike

是否可以通过单击事件更改网格布局?我有一个三行的网格显示,我希望在单击行中的元素时将网格更改为三列。

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

关于javascript - 单击事件更改网格布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55739798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com