我有一個使用 CSS 網格的應用程式,它將包含可變數量的網格元素,盡管我會知道每行中的專案數 - 是否有一種簡單的方法來確定給定專案的列數?
IE。給定 32 個元素排列成 8 行,第 9 個元素在第 1 列,第 10 個元素在第 2 列。
目前我正在這樣做:
function getColumn(itemIndex, colsPerRow) {
// its in the last column
if (itemIndex % colsPerRow === 0) {
return colsPerRow;
}
return itemIndex - (Math.floor(itemIndex/colsPerRow) * colsPerRow);
}
它會回傳正確的答案,但我覺得有一種更簡單的方法可以解決這個問題。
uj5u.com熱心網友回復:
考慮從 1 開始的編號:
column = (itemIndex - 1) % colsPerRow 1
if(從句中不需要)
uj5u.com熱心網友回復:
您幾乎已經得到了答案:專案編號模列數。
function getColumn(itemIndex, colsPerRow) {
// its in the last column
if (itemIndex % colsPerRow === 0) {
return colsPerRow;
}
return itemIndex % colsPerRow;
}
console.log(
getColumn(1,9),
getColumn(2,9),
getColumn(3,9),
getColumn(4,9),
getColumn(5,9),
getColumn(6,9),
getColumn(7,9),
getColumn(8,9),
getColumn(9,9),
getColumn(10,9),
getColumn(11,9)
);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/480378.html
標籤:javascript 数学
上一篇:在陣列Js中映射陣列
