我有一个相对定位的标题,当用户向下滚动页面时,我想切换到固定标题。这工作正常,只是标题最终覆盖了用户滚动到的元素。是否可以防止这种情况,使标题和元素之间的间隙保持不变以实现无缝过渡?
$(function() {
var hh = $('header').outerHeight();
$(window).scroll(function() {
var scroll = $(window).scrollTop();
var last = 0;
if (scroll >= hh) {
$('body').addClass('sticky');
} else {
$('body').removeClass('sticky');
}
last = scroll;
});
});
body,html {
margin:0;
}
.site-container {
position:relative;
width:90%;
height:1500px;
margin:0 auto;
background:gray;
}
img {
width:100%;
}
header {
display:flex;
flex-direction:column;
width:100%;
background:white;
}
body.sticky header {
position:fixed;
width:inherit;
}
.top-bar {
background:purple;
color:white;
padding:3px 0;
text-align:right;
}
ul {
margin:0;
padding-left:10px;
list-style-type:none;
}
li {
display:inline-block;
margin-left:10px;
line-height:30px;
}
li:first-child {
margin-left:0;
}
.site-content {
padding:50px 30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="site-container">
<header>
<div class="top-bar">(555) 555-5555</div>
<nav>
<ul>
<li>Home</li>
<li>Lorem</li>
<li>Ipsum</li>
</ul>
</nav>
</header>
<div class="site-content">
<img src="https://via.placeholder.com/800x400/0000FF/808080" />
</div>
</div>
有一个更简单的解决方案,仅使用 css,不需要 jQuery。 尝试CSS属性“position:sticky” - https://developer.mozilla.org/en-US/docs/Web/CSS/position
body,html {
margin:0;
}
.site-container {
position:relative;
width:90%;
height:1500px;
margin:0 auto;
background:gray;
}
img {
width:100%;
}
header {
display:flex;
flex-direction:column;
width:100%;
background:white;
position: sticky;
top: 0;
}
.top-bar {
background:purple;
color:white;
padding:3px 0;
text-align:right;
}
ul {
margin:0;
padding-left:10px;
list-style-type:none;
}
li {
display:inline-block;
margin-left:10px;
line-height:30px;
}
li:first-child {
margin-left:0;
}
.site-content {
padding:50px 30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="site-container">
<header>
<div class="top-bar">(555) 555-5555</div>
<nav>
<ul>
<li>Home</li>
<li>Lorem</li>
<li>Ipsum</li>
</ul>
</nav>
</header>
<div class="site-content">
<img src="https://via.placeholder.com/800x400/0000FF/808080" />
</div>
</div>
网站:https://www.w3schools.com/howto/howto_js_sticky_header.asp有在滚动上创建固定标题的步骤。这应该有助于添加额外的样式,这些样式可能需要添加以使标题流畅而不会像 @Oleg 的模拟那样闪烁。