我有一个问题仍然无法解决 Stack 中已经提出的任何问题。
我有一个粘性标题,当我移动时它会跳跃,我找不到解决方案。
我留下代码:
HTML
<header class="container-fluid" id="myHeader">
<div class="container">
<div class="row" id="encabezado">
<!--Here is a button that makes SlideToggle and shows content. Important to know so that elements do not overlap when you scroll and click on the button-->
</div>
</div>
</header>
JS:
// When the user scrolls the page, execute myFunction
window.onscroll = function() {myFunction()};
// Get the header
var header = document.getElementById("myHeader");
// Get the offset position of the navbar
var sticky = header.offsetTop;
// Add the sticky class to the header when you reach its scroll position. Remove "sticky" when you leave the scroll position
function myFunction() {
if (window.pageYOffset > sticky) {
header.classList.add("sticky");
} else {
header.classList.remove("sticky");
}
}
CSS:
.sticky {
-webkit-box-shadow: 0 6px 6px -6px #222;
-moz-box-shadow: 0 6px 6px -6px #222;
box-shadow: 0 6px 6px -6px #222;
position: fixed;
top: 0px;
width: 100%;
}
最佳答案
逻辑很简单,当您的导航变为“固定”时,它的高度会从主容器的高度中减去,从而导致尺寸减小。
例如,假设您的导航栏高 100 像素。 如果您的导航栏获得 .sticky 类,您的“内容”将失去 100 像素,导致您感觉到跳跃。
为了避免这种情况,您需要在给导航类 sticky 的同时,给您的内容区域一个带有 padding-top:100px 的类,例如,所以空间量 '被带走'被返回,因此感觉不到可感知的跳跃。
之后,为了使过渡更加顺畅,您需要将添加类的时间粘在导航栏与内容相交的精确偏移处。
更新:代码示例
根据您提供的信息,这是您代码的部分示例,不清楚您将其余内容(不包括标题)使用什么元素,我会假设这个元素是一个带有 class="content "和 id="我的内容"
CSS
.content.top-padding { padding-top: 100px; }
JavaScript
// When the user scrolls the page, execute myFunction
window.onscroll = function() {myFunction()};
// Get the header
var header = document.getElementById("myHeader");
// Get the content area
var content = document.getElementById("myContent");
// Get the offset position of the navbar
var sticky = header.offsetTop;
// Add the sticky class to the header when you reach its scroll position. Remove "sticky" when you leave the scroll position
function myFunction() {
if (window.pageYOffset > sticky) {
// here you add sticky -> also add top padding
header.classList.add("sticky");
header.classList.add("top-padding");
} else {
// here you remove sticky -> also remove top padding
header.classList.remove("sticky");
header.classList.remove("top-padding");
}
}
关于jquery - 滚动期间粘性标题跳转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54227379/