[英]How to prevent jumping of the content on changing elements position from relative to fixed
我想知道如何防止跳跃并使内容平滑过渡,因为我有一个元素可以将其位置从相对更改为固定。 我在这里弄了个小提琴。 我创建了3个元素:
<div id="top-bar">
<p>
Top bar
</p>
</div>
<div id="header">
<p>
Header
</p>
</div>
<div id="content">
<p>
Content
</p>
</div>
我尝试在top-bar
的height
上添加margin-top
,当top-bar
消失并且header
获得fixed
到content
元素的位置时,但这没有帮助。 如何在不跳内容的情况下使其顺畅?
解决方案的问题是因为您的margin-top类具有40px的页边距,而标头为100px高。 您也可以更改边距以匹配标题高度。
参见https://jsfiddle.net/8q6rbzj7/35/
.margin-top {
margin-top: 100px;
}
最好采用最简单的方法,只需使用与标头相同高度的包装器包装标头即可。
https://jsfiddle.net/8q6rbzj7/33/
<div class="header-container">
<div id="header">
<p>
Header
</p>
</div>
</div>
CSS
.header-container {
height: 100px;
}
减少了JS,因为您不需要该保证金
window.addEventListener('scroll', function() {
if (window.scrollY > headerTop) {
header.classList.add('fixed');
} else {
header.classList.remove('fixed');
}
});
你可以简单地做价值margin-top
相同值作为height
头 (100像素),而不是最上面一栏的,因为你必须添加你删除的内容。
const header = document.querySelector('#header'); const content = document.querySelector('#content'); const rect = header.getBoundingClientRect(); const scrollTop = window.pageYOffset || document.documentElement.scrollTop; const headerTop = rect.top + scrollTop; window.addEventListener('scroll', function() { if (window.scrollY > headerTop) { header.classList.add('fixed'); content.classList.add('margin-top'); } else { header.classList.remove('fixed'); content.classList.remove('margin-top'); } });
body,html { margin:0; } #top-bar { height: 40px; background: red; } #header { height: 100px; background: black; position: relative; top: 0; width: 100%; } #content { height: 900px; background: blue; padding-top: 150px; } .fixed { position: fixed!important; } .margin-top { margin-top: 100px; } p { color: white; } #top-bar p,#header p { margin:0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="top-bar"> <p> Top bar </p> </div> <div id="header"> <p> Header </p> </div> <div id="content"> <p> Content </p> <p> Content </p> <p> Content </p> <p> Content </p> <p> Content </p> <p> Content </p> <p> Content </p> <p> Content </p> <p> Content </p> <p> Content </p> <p> Content </p> <p> Content </p> <p> Content </p> <p> Content </p> <p> Content </p> <p> Content </p> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.