在滚动时固定标题 [英] Fixed header while scroll

查看:166
本文介绍了在滚动时固定标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在页面中间有一个表头,但是由于页面很大,我想把页眉固定在浏览器的顶部,而向下滚动页面...

I have the header of a table in the middle of a page, but since the page is huge, I want to fix the header to the top of browser while I scroll down for the page...

所以我的问题是:如何设置标题为正常,直到用户向下滚动,标题的顶部边框触及浏览器边框,它应该保持固定在那个位置,没有

So my question is: How do I set header to be normal, until the user scrolls down and the top border of header touches the browser border, where it should stay fixed on that position, no matter how much further down the user scrolls?

推荐答案

让我解释一下如何做到这一点。

Let me explain as to how this could be done.


  1. 找到您的表格标题,并保存其 code>

  2. 向窗口的滚动添加监听器。

  3. 对于表头部位置的窗口滚动
  1. Find your table header, and save its position
  2. Add a listener to the window's scroll event.
  3. Check the window scroll against your table header position

  1. 如果位置<窗口滚动 - 添加一个类来修复表头

  2. 否则,将css重置为正常表头。


我发布了一个小调,您可以在这里找到

<div class='lots_of_stuff_in_here'> ... </div>
<table>
    <thead id='my_fixable_table_header'>
        <tr>
            <th>My awsesome header number 1</th>
            <th>My awsesome header number 2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Content</td>
            <td>Content</td>
        </tr>
        // much more content
    </tbody>
</table>



Javascript



Javascript

// Just so you get the idea behind the code

var myHeader = $('#my_fixable_table_header');
myHeader.data( 'position', myHeader.position() );
$(window).scroll(function(){
    var hPos = myHeader.data('position'), scroll = getScroll();
    if ( hPos.top < scroll.top ){
        myHeader.addClass('fixed');
    }
    else {
        myHeader.removeClass('fixed');
    }
});

function getScroll () {
    var b = document.body;
    var e = document.documentElement;
    return {
        left: parseFloat( window.pageXOffset || b.scrollLeft || e.scrollLeft ),
        top: parseFloat( window.pageYOffset || b.scrollTop || e.scrollTop )
    };
}

这篇关于在滚动时固定标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆