如何在滚动上修复标题

How to fix a header on scroll(如何在滚动上修复标题)

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

问题描述

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

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


推荐答案

你需要一些 JS 来做滚动事件.最好的方法是为固定位置设置一个新的 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');
});

小提琴示例:http://jsfiddle.net/gxRC9/501/

扩展示例

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

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

扩展示例小提琴:http://jsfiddle.net/gxRC9/502/

这篇关于如何在滚动上修复标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在滚动上修复标题

基础教程推荐