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

后端 未结 11 1880
北荒
北荒 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

    While you can calculate which element you're looking for, I suggest you search for the element below. The benefit of this is that it would even work if your elements dont have the same width.

    So lets think about the attributes of the element below are. Essentially its the first element with a higher offsetTop and the same offsetLeft. You can do something like this to find the element ontop:

    const active = document.querySelector('.item.active');
    const all = [...document.querySelectorAll('.item')]
    const below = all
      .filter(c => c.offsetTop > active.offsetTop)
      .find(c => c.offsetLeft >= active.offsetLeft)
    const ontop = [...all].reverse()
      .filter(c => c.offsetTop < active.offsetTop)
      .find(c => c.offsetLeft >= active.offsetLeft)
    

提交回复
热议问题