jQuery 向下滚动后的粘性标题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18382496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sticky Header after scrolling down
提问by Nepo Znat
I saw this sticky header on this website: http://dunked.com/(no longer active, view archived site)
我在这个网站上看到了这个粘性标题:http: //dunked.com/ (不再活跃,查看存档站点)
When you scroll down the sticky header comes down from the top.
当您向下滚动时,粘性标题从顶部向下。
I looked at the code, but it looks really complicated. I only understand this: The normal header was cloned with JS and when you scroll down the page it animates from top.
我看了看代码,但看起来真的很复杂。我只明白这一点:普通的标题是用 JS 克隆的,当你向下滚动页面时,它会从顶部开始动画。
回答by Ian Clark
Here's a start. Basically, we copy the header on load, and then check (using .scrollTop()
or window.scrollY
) to see when the user scrolls beyond a point (e.g. 200pixels). Then we simply toggle a class (in this case .down
) which moves the original into view.
这是一个开始。基本上,我们在加载时复制标题,然后检查(使用.scrollTop()
或window.scrollY
)以查看用户何时滚动超过一个点(例如 200 像素)。然后我们简单地切换一个类(在这种情况下.down
)将原始移动到视图中。
Lastly all we need to do is apply a transition: top 0.2s ease-in
to our clone, so that when it's in the .down
state it slides into view. Dunked does it better, but with a little playing around it's easy to configure
最后,我们需要做的就是将 atransition: top 0.2s ease-in
应用于我们的克隆,这样当它处于这种.down
状态时,它就会滑入视图中。Dunked 做得更好,但稍微玩一下就很容易配置
CSS
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;
}
eitherVanilla JS(polyfill as required)
任一香草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));
orjQuery
或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));
});
});
Newer Reflections
较新的思考
Whilst the above answers the OP's original question of "How does Dunked achieve this effect?", I wouldn't recommend this approach. For starters, copying the entire top navigation could be pretty costly, and there's no real reason why we can't use the original (with a little bit of work).
虽然以上回答了 OP 的原始问题“Dunked 如何达到这种效果?” ,我不会推荐这种方法。对于初学者来说,复制整个顶部导航可能会非常昂贵,而且我们没有真正的理由不能使用原始导航(需要做一点工作)。
Furthermore, Paul Irish and others, have written abouthow animating with translate()
is better than animating with top
. Not only is it more performant, but it also means that you don't need to know the exact height of your element. The above solution would be modified with the following (See JSFiddle):
此外,爱尔兰的保罗等人,都写了关于如何用动画translate()
优于与动画top
。它不仅性能更高,而且还意味着您不需要知道元素的确切高度。将使用以下内容修改上述解决方案(请参阅 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);
}
The only drawback with using transforms is, that whilst browser support is pretty good, you'll probably want to add vendor prefixed versions to maximize compatibility.
使用转换的唯一缺点是,虽然浏览器支持非常好,但您可能希望添加供应商前缀版本以最大限度地提高兼容性。
回答by joevallender
Here is a JS fiddle http://jsfiddle.net/ke9kW/1/
这是一个 JS 小提琴http://jsfiddle.net/ke9kW/1/
As the others say, set the header to fixed, and start it with display: none
正如其他人所说,将标题设置为固定,并以 display: none 开始
then jQuery
然后是jQuery
$(window).scroll(function () {
if ( $(this).scrollTop() > 200 && !$('header').hasClass('open') ) {
$('header').addClass('open');
$('header').slideDown();
} else if ( $(this).scrollTop() <= 200 ) {
$('header').removeClass('open');
$('header').slideUp();
}
});
where 200 is the height in pixels you'd like it to move down at. The addition of the open class is to allow us to run an elseif instead of just else, so some of the code doesn't unnecessarily run on every scrollevent, save a lil bit of memory
其中 200 是您希望它向下移动的高度(以像素为单位)。添加 open 类是为了让我们可以运行 elseif 而不仅仅是 else,所以一些代码不会不必要地在每个滚动事件上运行,节省一点内存
回答by eagor
Here's is quite a list of jQuery pluginsthat will help achieve similar effect: http://jquery-plugins.net/tag/sticky-scroll
这里有很多jQuery 插件可以帮助实现类似的效果:http: //jquery-plugins.net/tag/sticky-scroll
回答by Franklyn Roth
I used jQuery .scroll() function to track the event of the toolbar scroll value using scrollTop. I then used a conditional to determine if it was greater than the value on what I wanted to replace. In the below example it was "Results". If the value was true then the results-label added a class 'fixedSimilarLabel' and the new styles were then taken into account.
我使用 jQuery .scroll() 函数使用 scrollTop 跟踪工具栏滚动值的事件。然后我使用条件来确定它是否大于我想要替换的值。在下面的示例中,它是“结果”。如果该值为真,则结果标签会添加一个类“fixedSimilarLabel”,然后会考虑新样式。
$('.toolbar').scroll(function (e) {
//console.info(e.currentTarget.scrollTop);
if (e.currentTarget.scrollTop >= 130) {
$('.results-label').addClass('fixedSimilarLabel');
}
else {
$('.results-label').removeClass('fixedSimilarLabel');
}
});
回答by Shiv Singh
I suggest to use sticky js it's have best option ever i have seen. nothing to do just ad this js on you
我建议使用粘性 js,这是我见过的最佳选择。没什么可做的,只是在你身上广告这个 js
https://raw.githubusercontent.com/garand/sticky/master/jquery.sticky.js
and use below code :
并使用以下代码:
<script>
$(document).ready(function(){
$("#sticker").sticky({topSpacing:0});
});
</script>
Its git repo: https://github.com/garand/sticky
它的 git 仓库:https: //github.com/garand/sticky
回答by Musaib Memdu
window bottom scroll to top scroll using jquery.
使用 jquery 将窗口底部滚动到顶部滚动。
<script>
var lastScroll = 0;
$(document).ready(function($) {
$(window).scroll(function(){
setTimeout(function() {
var scroll = $(window).scrollTop();
if (scroll > lastScroll) {
$("header").removeClass("menu-sticky");
}
if (scroll == 0) {
$("header").removeClass("menu-sticky");
}
else if (scroll < lastScroll - 5) {
$("header").addClass("menu-sticky");
}
lastScroll = scroll;
},0);
});
});
</script>
回答by Anup
css:
css:
header.sticky {
font-size: 24px;
line-height: 48px;
height: 48px;
background: #efc47D;
text-align: left;
padding-left: 20px;
}
JS:
JS:
$(window).scroll(function() {
if ($(this).scrollTop() > 100){
$('header').addClass("sticky");
}
else{
$('header').removeClass("sticky");
}
});
回答by Megan
This was not working for me in Firefox.
这在 Firefox 中对我不起作用。
We added a conditional based on whether the code places the overflow at the html level. See Animate scrollTop not working in firefox.
我们根据代码是否将溢出置于 html 级别添加了一个条件。请参阅Animate scrollTop 在 firefox 中不起作用。
var $header = $("#header #menu-wrap-left"),
$clone = $header.before($header.clone().addClass("clone"));
$(window).on("scroll", function() {
var fromTop = Array();
fromTop["body"] = $("body").scrollTop();
fromTop["html"] = $("body,html").scrollTop();
if (fromTop["body"])
$('body').toggleClass("down", (fromTop["body"] > 650));
if (fromTop["html"])
$('body,html').toggleClass("down", (fromTop["html"] > 650));
});
回答by Matt Saunders
a similar solution using jquery would be:
使用 jquery 的类似解决方案是:
$(window).scroll(function () {
$('.header').css('position','fixed');
});
This turns the header into a fixed position element immediately on scroll
这将在滚动时立即将标题变为固定位置元素
回答by mrdnk
Add debouncing, for efficiency http://davidwalsh.name/javascript-debounce-function
添加去抖动,以提高效率http://davidwalsh.name/javascript-debounce-function