如何在滚动上修复标题

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/

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

JS/HTML5 WebSocket: Connect without HTTP call(JS/HTML5 WebSocket:无需 HTTP 调用即可连接)
Getting #39;400 Bad Request#39; when using multipart/form-data as Content-Type in XHR(在 XHR 中使用 multipart/form-data 作为 Content-Type 时收到“400 Bad Request)
CSS: Repeat Table Header after Page Break (Print View)(CSS:分页后重复表头(打印视图))
Why put JavaScript in the footer of a page?(为什么将 JavaScript 放在页面的页脚中?)
Accessing [Symbol(Response internals)] from JSON response(从 JSON 响应访问 [Symbol(Response internals)])
Put HTML head in another file(将 HTML 头放在另一个文件中)