search

Home  >  Q&A  >  body text

JS/VueJS implementation of determining the currently visible top and bottom rows in an HTML table

I have a standard HTML table which contains thead and tbody, the number of rows in tbody can be any number as it depends on the size of the array.

The table has a maximum height so it can be scrolled. As the table scrolls, I want to be able to calculate the newly displayed top and bottom rows.

Also, I can't use jquery to achieve this, I just want to use javascript.

I tried the accepted answer to this question but it seems inaccurate and sometimes incorrectly counts the number of rows 2-7... Determining the top row in an html table

P粉103739566P粉103739566446 days ago530

reply all(1)I'll reply

  • P粉161939752

    P粉1619397522023-09-11 10:49:50

    You can use the IntersectionObserver API to check which rows are visible in the parent table. Add an intersection observer for each row and use isIntersecting to check if the row is visible.

    const rows = document.querySelector('.row')
    
    const rowsObserver = new IntersectionObserver(entries => {
          entries.forEach((entry) => {
            if (entry.isIntersecting) {
              (在这里添加您的代码)
            } else {
              (在这里添加您的代码)
            }
          })
        })
    
    rowsObserver.observe(rows)

    To count the first and last visible rows, you can add or remove each row to a "visibleElements" array when their visibility changes, or switch a "visible" class.

    reply
    0
  • Cancelreply