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

后端 未结 25 2653
悲&欢浪女
悲&欢浪女 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:36

    Well, I was trying to obtain the same effect without resorting to fixed size columns or having a fixed height for the entire table.

    The solution I came up with is a hack. It consists of duplicating the entire table then hiding everything but the header, and making that have a fixed position.

    HTML

    Col1 Col2 Col3
    info info info
    info info info
    info some really long line here instead info
    info info info
    info info info
    info info info
    info info info

    CSS

    body { height: 1000px; }
    thead{
        background-color:white;
    }
    

    javascript

    function moveScroll(){
        var scroll = $(window).scrollTop();
        var anchor_top = $("#maintable").offset().top;
        var anchor_bottom = $("#bottom_anchor").offset().top;
        if (scroll>anchor_top && scroll

    See here: http://jsfiddle.net/QHQGF/7/

    Edit: updated the code so that the thead can receive pointer events(so buttons and links in the header still work). This fixes the problem reported by luhfluh and Joe M.

    New jsfiddle here: http://jsfiddle.net/cjKEx/

提交回复
热议问题