gpt4 book ai didi

javascript - 如何使用 JavaScript 查找 CSS 网格布局元素放置在哪一列中

转载 作者:行者123 更新时间:2023-12-05 06:38:32 26 4
gpt4 key购买 nike

如果我使用 grid-template-columns: repeat(3, 1fr) 将一些 HTML 元素放入 3 列网格中,是否可以使用 JavaScript 找到元素的列?一些元素也跨越多行,因此元素的索引不一定与其列匹配。

例如:

const myElement = document.querySelector('div:nth-child(5)');

myElement.style.background = '#f00';

const columnIndex = 1; // How do I find this?
console.log('myElement is in column ' + columnIndex);
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 30px;
}

.item,
.item-large {
padding: 30px;
background: #3cf;
}

.item-large {
grid-row: span 2;
}
<div class="grid">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item-large"></div>
<div class="item">Which column am I in?</div>
<div class="item-large"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>

最佳答案

我在这里所做的是遍历所有元素,每次左侧位置增加并小于我的元素位置时,我都会增加一个计数器来跟踪该列。

我还修改了此处的代码片段,使其更具交互性。如果您单击 div,它会重新选择并显示新的列号。

var myElement = document.querySelector('div:nth-child(5)');
const allElements = document.querySelector('.grid').querySelectorAll('div');


//myElement.style.background = '#f00';
myElement.classList.add('item-found');

function showFound() {
let maxcolpos = -1, colposCount = 0;

for(elem of allElements) {
let l = elem.getBoundingClientRect().left;
if (l > maxcolpos) {
maxcolpos = l;
if (myElement.getBoundingClientRect().left > l) colposCount ++;
}
}

const columnIndex = colposCount + 1; //zero based, leave +1 if you want 0 based
myElement.innerText = 'Column = ' + columnIndex;
}

showFound();

document.querySelector('.grid').addEventListener("click", function(e) {
if (e.target && !e.target.matches(".grid")) {
myElement.classList.remove('item-found');
myElement.innerText = '';
myElement = e.target;
myElement.classList.add('item-found');
showFound();
}
});
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 30px;
}

.item,
.item-large {
padding: 30px;
background: #3cf;
}

.item-large {
grid-row: span 2;
}

.item-found {
background-color: red;
}
<div class="grid">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item-large"></div>
<div class="item"></div>
<div class="item-large"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>

关于javascript - 如何使用 JavaScript 查找 CSS 网格布局元素放置在哪一列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45870156/

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