如何在滚动上修复标题

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/

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

wkhtmltopdf print-media-type uses @media print ONLY and ignores the rest(Wkhtmltopdf print-media-type仅使用@media print,而忽略其余内容)
How to trim() white spaces from a string?(如何从字符串中去掉()空格?)
price depend on selection of radio input(价格取决于无线电输入的选择)
calculate price depend on selection without button(根据没有按钮的选择计算价格)
How to minify json response?(如何缩小JSON反应?)
Minify CSS with Node-sass(使用Node-Sass缩小CSS)