Table header to stay fixed at the top when user scrolls it out of view with jQuery

后端 未结 25 2539
悲&欢浪女
悲&欢浪女 2020-11-22 05:38

I am trying to design an HTML table where the header will stay at the top of the page when AND ONLY when the user scrolls it out of view. For example, the table may be 500

25条回答
  •  春和景丽
    2020-11-22 06:19

    This can be achieved by using style property transform. All you have to do is wrapping your table into some div with fixed height and overflow set to auto, for example:

    .tableWrapper {
      overflow: auto;
      height: calc( 100% - 10rem );
    }
    

    And then you can attach onscroll handler to it, here you have method that finds each table wrapped with

    :

      fixTables () {
        document.querySelectorAll('.tableWrapper').forEach((tableWrapper) => {
          tableWrapper.addEventListener('scroll', () => {
            var translate = 'translate(0,' + tableWrapper.scrollTop + 'px)'
            tableWrapper.querySelector('thead').style.transform = translate
          })
        })
      }
    

    And here is working example of this in action (i have used bootstrap to make it prettier): fiddle

    For those who also want to support IE and Edge, here is the snippet:

      fixTables () {
        const tableWrappers = document.querySelectorAll('.tableWrapper')
        for (let i = 0, len = tableWrappers.length; i < len; i++) {
          tableWrappers[i].addEventListener('scroll', () => {
            const translate = 'translate(0,' + tableWrappers[i].scrollTop + 'px)'
            const headers = tableWrappers[i].querySelectorAll('thead th')
            for (let i = 0, len = headers.length; i < len; i++) {
              headers[i].style.transform = translate
            }
          })
        }
      }
    

    In IE and Edge scroll is a little bit laggy... but it works

    Here is answer which helps me to find out this: answer

提交回复
热议问题