返回时OnScroll粘滞标题
OnScroll Sticky header while getting back
我创建了这个Fiddle:https://jsfiddle.net/empafmw8/
我的一切都很好,但当你滚动回网站顶部时,当你滚动到0时,.sticky-header
会将其position
更改为relative
。但我需要这样做,当.first
出现在屏幕上时。
如果.first
有height: 100%
,我也需要它来工作
我试过else if ($(window).scrollTop() == 800px)
或else if ($(window).scrollTop() == 100%)
之类的东西,但不起作用。
试试这个(请参阅我的更改注释):
$(document).ready(function() {
var firstHeight = $('.first').outerHeight(); // get the height of the /first div
//header
$(window).scroll(function() {
if ($(window).scrollTop() > $('.sticky-header').offset().top && !$('.sticky-header').hasClass('posi')) {
$('.sticky-header').addClass('posi');
} else if ($(window).scrollTop() <= firstHeight && $('.sticky-header').hasClass('posi')) { // remove the class if the height is less than or equal to the height of the first div
$('.sticky-header').removeClass('posi');
}
});
});
.first {
width: 100%;
height: 800px;
background: red;
}
.second {
width: 100%;
height: 2000px;
background: blue;
}
.sticky-header {
width: 100%;
height: 80px;
background-color: green;
}
.posi {
margin-top: 0;
top: 0;
position: fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first"></div>
<div class="second">
<div class="sticky-header"></div>
</div>
或者,您可以使用原始偏移顶部执行if-else操作-只需将hasClass
移动到其中:更新后的fiddle,它的效率更高
您可以尝试else if ($(window).scrollTop() < $('.second').offset().top)
-一旦.first
出现在屏幕上,这将使粘性标头返回到原来的位置。
小提琴示例。
相关文章:
- CSS-如何定位内容数据标题
- 在PHP中使用javascript更改页面标题'if'
- Brightcove获取/显示HTML中的当前视频标题和描述
- React组件-设置页面标题
- jQuery动态更改标题
- HighCharts长标题文本在某些元素上重叠
- 将行添加到具有固定标题的HTML表中
- CKEditor v4:自制插件中对话框的动态标题
- 如何在自动完成时设置属性标题
- 单元格的工具提示或标题不显示超过2000个字符
- 如何从相应的控制器动态更新标题和描述
- 将超链接添加到“;标题“;标记文本
- 为什么我会出现此错误"未捕获引用错误:未定义标题;
- FullCalendar:事件发生时阻止重叠.标题是一样的
- jQuery动画标题滚动
- 如何动态更改dataTablejQuery插件的列标题
- Wordpress标题和子菜单样式对IE的不满
- 正在尝试将标题标记添加到mailto链接,正文中包含URL
- 使用JavaScript将标题文本替换为按钮文本
- 返回时OnScroll粘滞标题