我有一个相对定位的标题,当用户向下滚动页面时,我想要移动到一个固定的标题。这很好,只是标题最终覆盖了用户滚动到的元素。是否有可能防止这种情况,使标题和元素之间的差距保持不变,以实现无缝转换?
$(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>
发布于 2022-08-12 00:01:50
有一个简单的解决方案,只使用css,而不需要jQuery。尝试css属性“位置:粘性”- 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://stackoverflow.com/questions/73327793
复制相似问题