jquery - 滚动期间粘性标题跳转

标签 jquery html css

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

相关文章:

javascript - 我有一张被 svg 遮盖的图像,我想让图像的遮盖部分不可点击

html - 使用css定位img元素

html - 具有最大宽度的元(用于图像)不起作用

javascript - 如何在 grid-auto-flow :column stick to each other? 中制作自动放置 div

javascript - 单击并向下滚动页面上的滑入式号召性用语 div buggy

jquery - 如何将样式/CSS 添加到简单的 jQuery Accordion ?

javascript - 按类别删除 div 的所有子级

javascript - 在 extjs 4 中加载期间取消选中整体 radio 组 radio 场

jquery - 如何从jquery数组对象中删除项目

html - IE 中的 Hr 标签 - 去除边框