javascript 滚动然后捕捉到顶部
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5124389/
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
scroll then snap to top
提问by mediarts
Just wondering if anyone has an idea as to how I might re-create a nav bar style that I saw a while ago, I just found the site I saw it on, but am not sure how they might have gotten there. Basically want it to scroll with the page then lock to the top...
只是想知道是否有人知道我如何重新创建我不久前看到的导航栏样式,我刚刚找到了我在其上看到的网站,但不确定他们是如何到达那里的。基本上希望它随着页面滚动然后锁定到顶部......
回答by mu is too short
Just do a quick "view source" on http://lesscss.org/and you'll see this:
只需在http://lesscss.org/上快速“查看源代码” ,您就会看到:
window.onscroll = function () {
if (!docked && (menu.offsetTop - scrollTop() < 0)) {
menu.style.top = 0;
menu.style.position = 'fixed';
menu.className = 'docked';
docked = true;
} else if (docked && scrollTop() <= init) {
menu.style.position = 'absolute';
menu.style.top = init + 'px';
menu.className = menu.className.replace('docked', '');
docked = false;
}
};
They're binding to the onscrollevent for the window, this event is triggered when the window scrolls. The dockedflag is set to true when the menu is "locked" to the top of the page, the menu is set to position:fixedat the same time that that flag is set to true. The rest is just some simple "are we about to scroll the menu off the page" and "are we about back where we started" position checking logic.
它们绑定到onscroll窗口的事件,当窗口滚动时触发此事件。docked当菜单“锁定”到页面顶部时,该标志设置为 true,菜单设置为position:fixed与该标志设置为 的同时true。剩下的只是一些简单的“我们是否要从页面上滚动菜单”和“我们是否要回到我们开始的地方”位置检查逻辑。
You have to be careful with onscrollevents though, they can fire a lotin rapid succession so your handler needs to be pretty quick and should precompute as much as possible.
onscroll但是,您必须小心处理事件,它们可以快速连续地触发很多,因此您的处理程序需要非常快,并且应该尽可能多地进行预计算。
In jQuery, it would look pretty much the same:
在 jQuery 中,它看起来几乎一样:
$(window).scroll(function() {
// Pretty much the same as what's on lesscss.org
});
You see this sort of thing quite often with the "floating almost fixed position vertical toolbar" things such as those on cracked.com.
您经常会在“浮动的几乎固定位置的垂直工具栏”中看到此类事情,例如cracked.com上的内容。
回答by jurrieb
mu is too short answer is working, I'm just posting this to give you the jquery script!
mu 太短的答案是有效的,我只是张贴这个给你 jquery 脚本!
var docked = false;
var menu = $('#menu');
var init = menu.offset().top;
$(window).scroll(function()
{
if (!docked && (menu.offset().top - $("body").scrollTop() < 0))
{
menu.css({
position : "fixed",
top: 0,
});
docked = true;
}
else if(docked && $("body").scrollTop() <= init)
{
menu.css({
position : "absolute",
top: init + 'px',
});
docked = false;
}
});
回答by ctietze
Mu's answer got me far. I tried my luck with replicationg lesscss.org's approach but ran into issues on browser resizing and zooming.Took me a while to find out how to react to that properly and how to reset the initial position (init) without jQuery or any other library.
穆的回答让我走得很远。我尝试使用 replicationg lesscss.org 的方法运气,但遇到了浏览器调整大小和缩放的问题。我花了一些时间才知道如何正确地对此做出反应以及如何在init没有 jQuery 或任何其他库的情况下重置初始位置 ( )。
Find a preview on JSFiddle:http://jsfiddle.net/ctietze/zeasg/
在 JSFiddle 上查找预览:http : //jsfiddle.net/ctietze/zeasg/
So here's the plain JavaScript code in detail, just in case JSFiddle refuses to work.
所以这里是详细的纯 JavaScript 代码,以防万一 JSFiddle 拒绝工作。
Reusable scroll-then-snap menu class
可重用的滚动然后捕捉菜单类
Here's a reusable version. I put the scrolling checks into a class because the helper methods involved cluttered my main namespace:
这是一个可重复使用的版本。我将滚动检查放入一个类中,因为涉及的辅助方法使我的主命名空间变得混乱:
var windowScrollTop = function () {
return window.pageYOffset;
};
var Menu = (function (scrollOffset) {
var Menu = function () {
this.element = document.getElementById('nav');
this.docked = false;
this.initialOffsetTop = 0;
this.resetInitialOffsetTop();
}
Menu.prototype = {
offsetTop: function () {
return this.element.offsetTop;
},
resetInitialOffsetTop: function () {
this.initialOffsetTop = this.offsetTop();
},
dock: function () {
this.element.className = 'docked';
this.docked = true;
},
undock: function () {
this.element.className = this.element.className.replace('docked', '');
this.docked = false;
},
toggleDock: function () {
if (this.docked === false && (this.offsetTop() - scrollOffset() < 0)) {
this.dock();
} else if (this.docked === true && (scrollOffset() <= this.initialOffsetTop)) {
this.undock();
}
}
};
return Menu;
})(windowScrollTop);
var menu = new Menu();
window.onscroll = function () {
menu.toggleDock();
};
Handle zoom/page resize events
处理缩放/页面调整大小事件
var updateMenuTop = function () {
// Shortly dock to reset the initial Y-offset
menu.undock();
menu.resetInitialOffsetTop();
// If appropriate, undock again based on the new value
menu.toggleDock();
};
var zoomListeners = [updateMenuTop];
(function(){
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0];
var lastWidth = 0;
function pollZoomFireEvent() {
var widthNow = w.innerWidth || e.clientWidth || g.clientWidth;
if (lastWidth == widthNow) {
return;
}
lastWidth = widthNow;
// Length changed, user must have zoomed, invoke listeners.
for (i = zoomListeners.length - 1; i >= 0; --i) {
zoomListeners[i]();
}
}
setInterval(pollZoomFireEvent, 100);
})();
回答by TheDeveloper
Sounds like an application of Jquery ScrollTop and some manipulation of CSS properties of the navbar element. So for example, under certain scroll conditions the navbar element is changed from absolute positioning with calculated co-ordinates to fixed positioning.
听起来像 Jquery ScrollTop 的应用程序和导航栏元素的 CSS 属性的一些操作。例如,在某些滚动条件下,导航栏元素从具有计算坐标的绝对定位更改为固定定位。
回答by Nimrod
The effect you describe would usually start with some type of animation, like in TheDeveloper's answer. Default animations typically slide an element around by changing its position over time or fade an element in/out by changing its opacity, etc.
您描述的效果通常以某种类型的动画开始,例如 TheDeveloper 的回答。默认动画通常通过随着时间的推移改变元素的位置来滑动元素,或者通过改变元素的不透明度等使元素淡入/淡出。
Getting the "bouce back" or "snap to" effect usually involves easing. All major frameworks have some form of easing available. It's all about personal preference; you can't really go wrong with any of them.
获得“弹回”或“对齐”效果通常涉及缓和。所有主要框架都有某种形式的缓动可用。这完全取决于个人喜好;他们中的任何一个你都不会出错。
jQuery has easing pluginsthat you could use with the .animate()function, or you can use jQueryUI.
jQuery 具有 可与该函数一起使用的缓动插件.animate(),或者您可以使用jQueryUI。
MooTools has easing built into the FX class of the core library.
MooTools在核心库的 FX 类中内置了缓动。
Yahoo's YUI also has easing built in.
雅虎的 YUI 也有内置的缓动。
If you can remember what site it was, you could always visit it again and take a look at their source to see what framework and effect was used.
如果你能记住它是什么网站,你可以随时再次访问它并查看它们的来源,看看使用了什么框架和效果。

