我在这个网站上看到了这个粘性标题: http://dunked.com/ (不再有效,view archived site)
当您向下滚动时,粘性标题会从顶部下降。
我看了代码,看起来确实很复杂。我只明白这个: 普通的标题是用 JS 克隆的,当你向下滚动页面时,它会从顶部开始动画。
最佳答案
<强> Here's a start 。基本上,我们在加载时复制标题,然后检查(使用 .scrollTop()
或 window.scrollY
)以查看用户何时滚动超出某个点(例如 200 像素) 。然后我们只需切换一个类(在本例中为 .down
),将原始内容移至 View 中。
最后,我们需要做的就是对我们的克隆应用一个 transition: top 0.2s Easy-in
,这样当它处于 .down
状态时,它会滑入看法。 Dunked 做得更好,但稍加尝试就可以轻松配置
CSS
header {
position: relative;
width: 100%;
height: 60px;
}
header.clone {
position: fixed;
top: -65px;
left: 0;
right: 0;
z-index: 999;
transition: 0.2s top cubic-bezier(.3,.73,.3,.74);
}
body.down header.clone {
top: 0;
}
两者都可以 Vanilla JS(根据需要进行填充)
var sticky = {
sticky_after: 200,
init: function() {
this.header = document.getElementsByTagName("header")[0];
this.clone = this.header.cloneNode(true);
this.clone.classList.add("clone");
this.header.insertBefore(this.clone);
this.scroll();
this.events();
},
scroll: function() {
if(window.scrollY > this.sticky_after) {
document.body.classList.add("down");
}
else {
document.body.classList.remove("down");
}
},
events: function() {
window.addEventListener("scroll", this.scroll.bind(this));
}
};
document.addEventListener("DOMContentLoaded", sticky.init.bind(sticky));
或 jQuery
$(document).ready(function() {
var $header = $("header"),
$clone = $header.before($header.clone().addClass("clone"));
$(window).on("scroll", function() {
var fromTop = $("body").scrollTop();
$('body').toggleClass("down", (fromTop > 200));
});
});
<小时/>
新的思考
虽然上面回答了OP最初的问题“Dunked如何实现这种效果?”,但我不推荐这种方法。对于初学者来说,复制整个顶部导航可能会非常昂贵,而且我们没有真正的理由不能使用原始导航(只需做一点工作)。
此外,Paul Irish 和其他人有 written about使用 translate()
制作动画比使用 top
制作动画效果更好。它不仅性能更高,而且还意味着您不需要知道元素的确切高度。上述解决方案将修改为以下 (See JSFiddle) :
header.clone {
position: fixed;
top: 0;
left: 0;
right: 0;
transform: translateY(-100%);
transition: 0.2s transform cubic-bezier(.3,.73,.3,.74);
}
body.down header.clone {
transform: translateY(0);
}
使用变换的唯一缺点是,同时 browser support is pretty good ,您可能需要添加 vendor 前缀版本以最大限度地提高兼容性。
关于javascript - 向下滚动后粘性标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18382496/