jquery - 中间的粘性标题

标签 jquery html css scroll sticky

我正在尝试在中间区域 中制作一个粘性 header 。当页面滚动到 <ul id="scroll-list"></ul> 时,它应该停留在顶部 元素。但是当页面滚动到 <div id="stop-sticky"></div>时,它一定不能停留在顶部。

我已经接近于遵循@izulito 的解决方案。

但是问题我在这个更新的解决方案中看到的是标题元素似乎移动到它的原始位置,我通过console.log($('#header').offset().top);验证了这一点, 滚动到 <div id="stop-sticky"></div>。它使标题 div 在转换时闪烁。

I want a smooth scroll in which header should disappear and reappear along with the scroll.

$( document ).ready(function() {
	var actualPosition = $('#header').offset().top;
	$(window).scroll(function (event) {
	console.log($('#header').offset().top);
  if($(window).scrollTop() > $('#stop-sticky').offset().top) {
      $('#header').addClass('nonstiky');
    } else {
          $('#header').removeClass('nonstiky');}
	});
});
#summary {
		  width: 100%;
		  height: 300px;
		  background: #ccc;
		}

		#header {
		  width: 100%;
		  height: 60px;
		  background: #fcc;
		  position: sticky;
		  top: 10px;
		}
    
    #header.nonstiky {
      position: relative
      }

		#scroll-list {
		  height: 500px;
		  background: #cc1;
		}
    #stop-sticky {
		  height: 1000px;
		  background: #c01;
		}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
	<div id="summary">Summary</div>
	<div id="header">Header</div>
	<ul id="scroll-list"></ul>
        <div id="stop-sticky"></div>
</body>

最佳答案

检查这段代码。当您滚动传递 stop-sticky id 时,我在您的标题中添加了一个类。

$( document ).ready(function() {
	var actualPosition = $('#header').offset().top;
	$(window).scroll(function (event) {
  if($(window).scrollTop() > $('#stop-sticky').offset().top) {
      $('#header').addClass('nonstiky');
    } else {
          $('#header').removeClass('nonstiky');}
	});
});
#summary {
		  width: 100%;
		  height: 300px;
		  background: #ccc;
		}

		#header {
		  width: 100%;
		  height: 60px;
		  background: #fcc;
		  position: sticky;
		  top: 10px;
		}
    
    #header.nonstiky {
      position: relative
      }

		#scroll-list {
		  height: 500px;
		  background: #cc1;
		}
    #stop-sticky {
		  height: 1000px;
		  background: #c01;
		}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
	<div id="summary">Summary</div>
	<div id="header">Header</div>
	<ul id="scroll-list"></ul>
        <div id="stop-sticky"></div>
</body>

关于jquery - 中间的粘性标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47928731/

相关文章:

css - 全屏 HTML5 部分背景视频

javascript - 如何在谷歌柱形图 api 中添加链接(可点击并获取新数据)

javascript - 从 .js/外部文件生成工具提示文本

php - 使用文件下载将数据从数据库导出到csv

css - 透明文本与CSS

html - CSS 过渡不起作用,但属性更改起作用

jQuery 使用可折叠内容向下移动 DIVS

javascript - 在 Jquery 中切换元素显示的可靠方法

javascript - 切换而不是使用 URL 进行分页

javascript - 类似 vlookup 的 javascript 将输入值从一个字段映射到另一个字段