我需要一个与父div相关的粘性标题。目前,Header只在部分div上是粘性的。但是我想要一个相对于父类的粘性头部。
HTML代码
<div class="parent">
<div class="section-one">
<h1>Header 1</h1>
<div class="content">
content 123
</div>
</div>
<div class="section-two">
<h1>Header 2</h1>
<div class="content">
content 789
</div>
</div>
<div class="section-three">
<h1>Header 3</h1>
<div class="content">
content 456
</div>
</div>
</div>这是我的css,
.parent {
position: relative;
}
.section-one h1{
position: sticky;
top: 0;
z-index: 9999;
}
.section-two h1{
position: sticky;
top: 50;
z-index: 9999;
}
.section-three h1{
position: sticky;
top: 100;
z-index: 9999;
}我想要一个粘性标题,如下所示
Header 1
Header 2
Header 3我想要一个每个图像粘性标题。

发布于 2020-11-09 14:03:51
$(window).scroll(function() {
var distanceFromTop = $(this).scrollTop();
if (distanceFromTop >= $('.section-one').offset().top) {
$('.section-one h1').addClass('fixed');
}
if (distanceFromTop >= $('.section-two').offset().top) {
$('.section-two h1').addClass('fixed');
}
if (distanceFromTop >= $('.section-three').offset().top) {
$('.section-three h1').addClass('fixed');
}
if (distanceFromTop >= $('.parent').height()) {
$('.section-one h1').removeClass('fixed');
$('.section-two h1').removeClass('fixed');
$('.section-three h1').removeClass('fixed');
}
});.parent {
position: relative;
}
.section-one,
.section-two,
.section-three { min-height: 100vh; }
.section-one { background: lightgray; }
.section-two { background: lightblue; }
.section-three { background: lightgreen; }
.section-one h1{
position: sticky;
top: 0;
z-index: 9999;
}
.section-two h1{
position: sticky;
top: 0;
z-index: 9999;
}
.section-three h1{
position: sticky;
top: 0;
z-index: 9999;
}
.section-one h1.fixed {
position: fixed;
top: 0px;
}
.section-two h1.fixed {
position: fixed;
top: 50px;
}
.section-three h1.fixed {
position: fixed;
top: 100px;
}<script type="text/javascript" src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<div class="parent">
<div class="section-one">
<h1>Header 1</h1>
<div class="content">
content 123
</div>
</div>
<div class="section-two">
<h1>Header 2</h1>
<div class="content">
content 789
</div>
</div>
<div class="section-three">
<h1>Header 3</h1>
<div class="content">
content 456
</div>
</div>
</div>
<div style="height: 100vh; background: green;"></div>
https://stackoverflow.com/questions/64746411
复制相似问题