[英]Docked menu on scroll - JavaScript probably required
这是我的代码: http : //jsfiddle.net/spadez/usbs2/19/
我正试着这样做,当我向下滚动时,黄色菜单停靠在页面顶部,当你从它向下滚动时,我相信你之前已经看到过这种东西了,类似这样的东西:
http://css-tricks.com/examples/PersistantHeaders/
我知道可以一直停靠一个标题,但是如何制作它以便只有在向下滚动以使其离开页面时才会出现。 我猜它需要某种jquery魔法?
HTML
<div id="main">
<div id="header">test</div>
<div id="jumbo">test</div>
<div id="select">menu</div>
<div id="features">1
<br />1
<br />1
<br />1
<br />1
<br />1
<br />1
<br />1
<br />1
<br />1
<br />1
<br />1
<br />1
<br />1
<br />1
<br />
</div>
</div>
您可以使用jQuery,只需稍微更改一下CSS:
// get initial top position of menu
var init = $('#select').offset().top;
// listen to window scroll event
$(window).scroll(function () {
// if top of window scrolled past top of menu
if ($(window).scrollTop() > init) {
// fix the menu to the top of the page
$('#select').css({
top: 0,
position: 'fixed'
});
} else {
// otherwise put it back in its regular position
$('#select').css('position','relative');
}
});
CSS
html, body {
height: 100%;
width:100%; /* <-- defined default width */
margin: 0;
padding: 0;
}
#main {
height: 100%;
width: 100%;
}
#header {
height: 60px;
background: pink;
float: left;
width: 100%;
}
#jumbo {
height: 100%;
background: blue;
}
#select {
height: 60px;
background-color:yellow;
width:100%; /* <-- set width (relative to body) */
}
如果你添加position:fixed;
像#header
一样,它将自动保持在顶部。 如果标题不需要始终位于顶部(例如,当标题上方有某些内容允许滚动屏幕时),您可能需要一个脚本来添加或删除包含此css属性的类。
另一个答案使用jQuery,这是它的非jQuery版本:
var select = document.querySelector('#select');
var initialPosition = select.offsetTop;
addEventListener('scroll', function (event) {
if (window.scrollY > initialPosition) {
select.classList.add('fixed');
} else if (select.classList.contains('fixed')) {
select.classList.remove('fixed');
}
});
当然,将类添加到样式表中:
.fixed {
position:fixed;
top:0;
}
这是一个显示工作脚本的jsfiddle
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.