如何在滚动上固定标题 [英] How to fix a header on scroll

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

问题描述

我创建一个标题,一旦滚动到一定量的像素,它修复并保持在原地。

I am creating a header that once scrolled to a certain amount of pixels it fixes and stays in place.

我可以使用css和html或者我需要jquery吗?

Can I do this using just css and html or do i need jquery too?

我创建了一个演示,以便您可以理解。任何帮助将是巨大的!

I have created a demo so you can understand. Any help would be great!

http://jsfiddle.net/gxRC9/ 4 /

body{
    margin:0px;
    padding:0px;
}
.clear{
    clear:both;
}
.container{
    height:2000px;
}
.cover-photo-container{
width:700px;
height: 348px;
margin-bottom: 20px;
background-color:red;
}

.small-box{
    width:163px;
    height:100px;
    border:1px solid blue;
    float:left;
}

.sticky-header{
    width:700px;
    height:50px;
    background:orange;
    postion:fixed;
}


推荐答案

滚动事件。最好的方法是为固定位置设置一个新的CSS类,当滚动超过某一点时,该类将被分配给相关的div。

You need some JS to do scroll events. The best way to do this is to set a new CSS class for the fixed position that will get assigned to the relevant div when scrolling goes past a certain point.

HTML

<div class="sticky"></div>

CSS

.fixed {
    position: fixed;
    top:0; left:0;
    width: 100%; }

jQuery

$(window).scroll(function(){
  var sticky = $('.sticky'),
      scroll = $(window).scrollTop();

  if (scroll >= 100) sticky.addClass('fixed');
  else sticky.removeClass('fixed');
});

示例fiddle: http://jsfiddle.net/gxRC9/501/

编辑:扩展示例

如果触发点未知,但应该是当粘性元素到达屏幕顶部时, offset 可以使用。

If the trigger point is unknown but should be whenever the sticky element reaches the top of the screen, offset().top can be used.

var stickyOffset = $('.sticky').offset().top;

$(window).scroll(function(){
  var sticky = $('.sticky'),
      scroll = $(window).scrollTop();

  if (scroll >= stickyOffset) sticky.addClass('fixed');
  else sticky.removeClass('fixed');
});

扩展示例fiddle: http://jsfiddle.net/gxRC9/502/

Extended example fiddle: http://jsfiddle.net/gxRC9/502/

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

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