jquery - 具有向下滑动效果的粘性标题

标签 jquery css sticky

我希望当我向上滚动时我的页面标题也会上升但是在滚动位置 150 之后它会平滑地向下滑动并固定在顶部。我尝试了很多方法,但没有真正得到正确的结果。请大家看看我的代码好吗?

像这样的东西 http://cssdeck.com/labs/sticky-header-with-slide-down-effect这个脚本有一些小故障。

jQuery(document).ready(function ($) {
    $(window).scroll(function () {

        if ($(window).scrollTop() >= 100) {
            $('.navarea').addClass('fixed-header');

        } else {
            $('.navarea').removeClass('fixed-header');
        }
    });
});

这是CSS

.navarea {

    z-index: 2;
    background: rgba(255, 255, 255, 0.9);
    transition: all 0.5s ease-in-out;
}

.fixed-header {
    position: fixed;
    background: rgba(255, 255, 255, 0.9);
    text-shadow: none;
    padding-bottom: 0;
    top: 0;
    z-index: 5;
    transition: all 0.5s ease-in-out;
}

实时网址: https://codepen.io/pagol/pen/XovvGJ

最佳答案

举个例子

  • 创建导航元素的深度克隆(其他解决方案在大量测试后出现错误)
  • 使用 CSS3 transition 进行克隆导航
  • 使用去抖动回调机制来利用滚动时触发的函数
  • 对原始元素使用position stickyvisibility来提升效果

// https://github.com/micro-js/debounce/blob/master/lib/index.js
function debounce(fn, time) {
  var pending = null
  return function() {
    if (pending) clearTimeout(pending)
    pending = setTimeout(run, time)
    return function() {
      clearTimeout(pending)
      pending = null
    }
  }
  function run() {
    pending = null
    fn()
  }
}

function documentScrollTop() {
  const doc = document.documentElement;
  return (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
}

const el_nav1 = document.getElementById("nav");
const el_nav2 = el_nav1.cloneNode(true);
el_nav1.parentNode.insertBefore(el_nav2, el_nav1);
el_nav2.style.cssText = `position:fixed; transform:translateY(-100%);`;

function animateNavigation() {
  const canShow = documentScrollTop() >= 150;
  el_nav2.style.transform = `translateY(${canShow?0:-100}%)`;
  el_nav1.style.cssText = `position:${canShow?'sticky':'relative'}; visibility:${canShow?'hidden':'visible'};`
}

window.addEventListener('scroll', debounce(animateNavigation, 99));
document.addEventListener('DOMContentLoaded', animateNavigation);
/*QuickReset*/ *{margin:0;box-sizing:border-box;} html,body{height:100%;font:14px/1.4 sans-serif;}
p {height:300vh;border:4px dashed #000;} /* force scrollbars */

#nav {
  position: relative;
  top: 0;
  width: 100%;
  padding: 20px;
  background: gold;
  transition: transform 0.6s;
}
<nav id="nav">NAVIGATION HERE</nav>
<p></p>

改进空间

  • 尝试只使用一个元素(这里很难滚动回到顶部...)
  • animateNavigation 函数中使用一个额外的条件来测试一个 Action 是否已经执行(以防止对 style 的额外调用,直到 canShow 切换到一个新的 bool 值)

关于jquery - 具有向下滑动效果的粘性标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54279860/

相关文章:

javascript - php 在发布时在变量末尾丢失了+(加号)

jquery - 与 mongo 和 Node js 不同

css - 如何不将样式应用于第一次无效的输入元素

javascript - 滚动上的粘性 div

css - 如何在Bootstrap 4中使左右网格粘性,中间网格可滚动

css - 当粘性元素在容器内时保持粘性定位行为(因为 React 必须渲染单个父元素)

javascript - 滚动条在jstree中不断向下滚动

jquery - 使用 jQuery 从对象数组中添加表元素

html - 当 ui :insert is used 时使页脚贴在页面底部

html - 我想使用 CSS 在 html 中水平添加许多图像