首页 > 解决方案 > 滚动期间粘性标题跳跃

问题描述

我有一个问题仍然无法解决 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%;

}

标签: jqueryhtmlcss

解决方案


逻辑很简单,当您的导航变为“固定”时,它的高度会从主容器的高度中减去,从而导致尺寸减小。

例如,假设您的导航栏高 100 像素。如果您的导航栏获得 .sticky 类,您的“内容”会丢失 100 像素,从而导致您感觉到跳跃。

为了避免这种情况,你需要,在你给导航类粘性的同时,你必须给你的内容区域一个具有 padding-top:100px 的类,例如,所以空间量“带走”被返回,因此感觉不到可感知的跳跃。

之后,为了使过渡更加平滑,您需要将粘性类添加到导航栏与内容相遇的精确偏移量。

更新:代码示例

根据您提供的信息,这是您的代码的部分示例,尚不清楚您将什么元素用于其余内容(不包括标题),我将假设该元素是一个 with 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");
  }
}

推荐阅读