JS/VueJS implementation of determining the currently visible top and bottom rows in an HTML table
P粉103739566
P粉103739566 2023-09-10 19:23:08

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粉103739566
P粉103739566

reply all(1)
P粉161939752

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!