我希望当我向上滚动时,页面标题也会上升,但是在滚动位置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;
}
答案 0 :(得分:0)
这是一个例子
transition
进行克隆导航position sticky
和visibility
作为原始元素以改善效果
// 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
函数内使用一个附加条件来测试是否已执行某项操作(以防止在style
切换到新的布尔值之前对canShow
的附加调用)