簡體   English   中英

CSS網格-計算列數(javascript)

[英]CSS grid - count number of columns (javascript)

我有一個CSS網格

.wrapper {
  display: grid;
  grid-template-columns: repeat(auto-fill, 12.5vw );
  grid-template-rows: repeat(auto-fill, 12.5vw );
  background-color: black;
  grid-auto-flow: row dense;
  color: #444;
}


<div class="wrapper">
 <div class="box wide tall a">
 </div>
 <div class="box b">
 </div>
 <div class="box c">
 </div>
 <div class="box c">
 </div>
 <div class="box d">
 </div>
 <div class="box e">
 </div>
 <div class="box f">
 </div>
 <div class="box g">
 </div>
 <div class="box h">
 </div>
</div>

我想知道我的JavaScript代碼中的列數。 可能嗎?

編輯:我想要這的原因是,如果少於足夠數量的項目,使它成為一個正方形,我希望這些額外的項目根本不顯示。

非常感謝!

您可以使用getElementsByClassName檢索所有box div並獲取數組長度:

var columns = document.getElementsByClassName('box').length

我認為您錯過了grid-template-columns:的minmax部分grid-template-columns:例如grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));

如果沒有它,您將始終有7列,並且網格列將不會響應,並且不會隨着頁面寬度的縮小/擴展而變化。

可以在此處查看Jen Simmons示例頁面: Spice Gallery布局

一種不需要任何javascript ..但需要一些媒體查詢的解決方案是用容器包裝.wrapper div。 並設置最大高度。 每個屏幕的斷點,當最后一行上的每個圖像都沒有偶數時。 然后設置.containeroverflow-y:hidden;

在此處鏈接到筆: 用CSS隱藏網格的最后一行

使用javascript進行此操作,您將需要知道有多少張圖片以及minmax列的寬度是多少。 大眾單位基本上是寬度(%)。 所以你需要做一些數學。 使用mod函數可以知道最后一行有多少個項目。 然后需要一種隱藏它們的方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM