一个粘性菜单栏,从底部开始,然后保持在顶部



我正在制作这个单页网站,在第一次打开时,整个屏幕都充满了一个大图像,菜单栏在屏幕底部。

当你向下滚动时,我希望菜单与内容一起滚动,但要粘在窗口顶部,永远不要滑出顶部边缘,以便始终可以访问。

我发现了许多"粘性菜单"脚本,它们做了一些接近它的事情,但它们总是从页面中间的菜单栏开始,而不是一个在开始时与底部对齐的菜单。

这是一把小提琴:

http://codepen.io/anon/pen/pREYeJ

我在里面使用了这个脚本:http://stickyjs.com/

就像我尝试过的所有其他方法一样,它并没有按预期工作。当你滚动时,菜单栏无法平滑滑动,只要你开始滚动,它就会跳到页面顶部。

我认为问题在于我正在使用

position: absolute;
bottom: 0;

在菜单栏的分区上

然而,当你第一次打开页面时,无论窗口大小,我都不知道如何坚持到窗口底部。

有什么想法吗?

您可以在CSS:中添加top值和transition

#menu{
/* trigger an animation when scripts updates CSS*/
top:calc(100% - 100px);/* cause scripts gives top:0 and erase bottom */
transition:1s;/* your transition */
height: 100px;
width: 100%;
position: absolute;
bottom: 0;
left: 0;
background-color: #009900; 
}

编辑

除此之外,您还可以从以下方面激励自己:https://www.sitepoint.com/css-position-sticky-introduction-polyfills/

对于这种结果http://codepen.io/anon/pen/xgEeye

位置:固定而不是绝对和这里的脚本更新:

//$(document).ready(function(){
//    $("#menu").sticky({topSpacing:0});
//  });
var menu =  document.querySelector('#menu');
var box =  document.querySelector('#screen2');
var boxPosition = box.getBoundingClientRect().top;
window.addEventListener('scroll', function() {
if (window.pageYOffset >= boxPosition) {
menu.style.top = '0px';
} else {
menu.style.top = 'calc(100% - 100px)';
}
});

var menu =  document.querySelector('#menu');
var box =  document.querySelector('#screen2');
var boxPosition = box.getBoundingClientRect().top;
window.addEventListener('scroll', function() {
if (window.pageYOffset >= boxPosition) {
menu.style.top = '0px';
} else {
menu.style.top = 'calc(100% - 100px)';
}
});
html,
body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
position: relative;
}
#screen1 {
min-height: 100%;
width: 100%;
margin: 0;
padding: 0;
background-color: #000;
}
#menu {
transition: 1s;
height: 100px;
width: 100%;
position: fixed;
bottom: 0;
left: 0;
top: calc(100% - 100px);
background-color: #009900;
border-top: 2px solid #333;
color: #fff;
text-align: center;
font-size: 20px;
}
#screen2 {
width: 100%;
background-color: #f4452a;
height: 1000px;
padding-top: 200px;
text-align: center;
}
<div id="screen1">
screen
</div>
<div id="menu">
THIS IS THE MENU
<br />and I don't want to abruptly jump to the top but to gently slide to it on scroll and then stick to it
</div>
<div id="screen2">
Rest of the page bla bla
<br />  <br />  <br />  <br />  <br />  <br />  <br />  <br />  <br />  <br />  <br />  <br />keep scrolling
</div>

最新更新