Javascript 滚动时固定标题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13795283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 12:55:05  来源:igfitidea点击:

Fixed header while scroll

javascriptjqueryhtmlcss

提问by Nutic

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?

所以我的问题是:如何将标题设置为正常,直到用户向下滚动并且标题的顶部边框接触浏览器边框,无论用户向下滚动多少,它都应该固定在该位置?

回答by Jibi Abraham

Let me explain as to how this could be done.

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

Steps

脚步

  1. Find your table header, and save its position
  2. Add a listener to the window's scrollevent.
  3. Check the window scroll against your table header position
    1. If the position < window scroll - add a class to fix the table header
    2. Else, reset the css to behave like a normal header.
  1. 找到你的表头,并保存它 position
  2. 为窗口的scroll事件添加一个监听器。
  3. 检查窗口滚动到您的表格标题位置
    1. 如果位置 < 窗口滚动 - 添加一个类来修复表头
    2. 否则,重置 css 使其表现得像一个普通的标题。

I've posted a fiddle that you can find here.

我已经发布了一个小提琴,你可以在这里找到

Code sample

代码示例

HTML

HTML

<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 )
    };
}

?

?

回答by Chris Like

You're looking for a horizontally oriented "sticky box" that follows you down the page as you scroll.

您正在寻找一个水平方向的“粘性框”,它会在您滚动时跟随您的页面。

Here is a walkthrough that explains how to create this effect for a sidebar: http://css-tricks.com/scrollfollow-sidebar/

这是一个演练,解释了如何为侧边栏创建这种效果:http: //css-tricks.com/scrollfollow-sidebar/

I modified the code to work with a generic example that spans the width of the page:

我修改了代码以使用跨越页面宽度的通用示例:

HTML:

HTML:

<div class="wrapper">
  <div class="head">HEAD</div>
  <div class="header">Table Header</div>
  <div class="content">Content</div>
  <div class="footer">Footer</div>
</div>?

CSS:

CSS:

.wrapper {
  border:1px solid red;
}
.head{
  height: 100px;
  background: gray;
}
.header {
  background:red;
  height:100px;
  left:0;
  right:0;
  top:0px;
  margin-top:100px;
  position:absolute;
}

.content {
   background:green;
   height:1000px;
}

.footer {
   background:blue;
   height:100px;
}

jQuery:

jQuery:

$(function() {

    var $sidebar = $(".header"),
        $window = $(window),
        offset = $sidebar.offset(),
        topPadding = 0;

    $window.scroll(function() {
        if ($window.scrollTop() > offset.top) {
            $sidebar.stop().animate({
                top: $window.scrollTop() - offset.top + topPadding
            });
        } else {
            $sidebar.stop().animate({
                top: 0
            });
        }
    });

});?

?This will animate the header block into view when you scroll beyond where it originally appears.

?当您滚动超出最初出现的位置时,这会将标题块动画化到视图中。

jsFiddle here

jsFiddle在这里

回答by Vainglory07

you may try to enclose the bottom elements under the header in one div then add class to that div set overflow to auto

您可以尝试将标题下的底部元素包含在一个 div 中,然后将类添加到该 div 设置溢出为自动

回答by Shailender Arora

I hope you are looking like this Header Fix Demo

我希望你看起来像这个 Header Fix Demo

HTML

HTML

<div class="wrapper">
<div class="header">Header Fix</div>
<div class="content">Content</div>
<div class="footer">Footer</div>
</div>

CSS

CSS

.wrapper {
  border:1px solid red;
}

.header {
  background:red;
  height:100px;
  position:fixed;
  left:0;
  right:0;
  top:0;

}

.content {
   background:green;
   height:1000px;
}

.footer {
   background:blue;
   height:100px;
}

回答by siddharth gupta

for keeping the position fixed of any block element,you need to use the absolute or the fixed property in the display attribute of style,but dont forget to give enough space and break to the top elements otherwise it will go under the header section.

为了保持任何块元素的位置固定,你需要在样式的显示属性中使用absolute或fixed属性,但不要忘记留出足够的空间并打破顶部元素,否则它会在标题部分下方。

回答by Anup

$(window).scroll(function() {
 if ($(this).scrollTop() > 100){  
    $('header').addClass("sticky");
  }
  else{
    $('header').removeClass("sticky");
  }
});

css:

css:

header.sticky {
  font-size: 24px;
  line-height: 48px;
  height: 48px;
  background: #efc47D;
  text-align: left;
  padding-left: 20px;
}

回答by Stefan Pintilie

Here is a full working version using fixed headers, footers and columns!

这是使用固定页眉、页脚和列的完整工作版本!

Apply the classes for position relative, very important, otherwise the fixed column will overlap the header and footer, then define the classes at the table level where needed: "sticky-table"(mandatory), "sticky-header", "sticky-column", "sticky-footer", than call function "applyStickyHeaders". That's all!

应用位置相关的类,非常重要,否则固定列将与页眉和页脚重叠,然后在需要的地方定义表级别的类:“sticky-table”(强制)、“sticky-header”、“sticky-” column”、“sticky-footer”,而不是调用函数“applyStickyHeaders”。就这样!

$(function(){
    applyStickyHeaders();
});

Full example:

完整示例:

https://jsfiddle.net/pintilies/6zLyxewg/4/

https://jsfiddle.net/pintilies/6zLyxewg/4/

Tested in IE, FireFox and Chrome.

在 IE、FireFox 和 Chrome 中测试。