如何使用JavaScript查找CSS网格布局元素的列

时间:2017-08-24 20:13:34

标签: javascript css

如果我使用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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

我在这里做的是循环遍历所有元素,每当左侧位置增加并且小于我的元素位置时,我增加一个计数器以跟踪列。

我还在这里修改了片段以使其更具互动性。如果单击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>