How to calculate the amount of flexbox items in a row?

后端 未结 11 1892
北荒
北荒 2020-12-04 12:12

A grid is implemented using the CSS flexbox. Example:

The number of rows in this example is 4 because I fixed the container width for demo purposes. But, in

11条回答
  •  余生分开走
    2020-12-04 12:43

    offsetTop is a popular method to determine the y-position of an element.

    If two adjacent sibling elements have the same y-position, we can safely assume that they are visually on the same row (since all the elements have the same height).

    Thus, we can start counting the number of elements in a row by comparing their y-positions one by one. We stop counting as soon as we run out of elements or we encounter an adjacent sibling with a different y-position.

    function getCountOfItemsInRow() {
        let grid = document.getElementById('grid').children; //assumes #grid exists in dom
        let n = 0; // Zero items when grid is empty
    
        // If the grid has items, we assume the 0th element is in the first row, and begin counting at 1
        if (grid.length > 0) {
            n = 1; 
    
            // While the nth item has the same height as the previous item, count it as an item in the row. 
            while (grid[n] && grid[n].offsetTop === grid[n - 1].offsetTop) {
                n++;
            }
        }
    
        return n;
    }
    

提交回复
热议问题