我需要快速完成twitter bootstraps主导航和子导航的功能,例如http://twitter.github.com/bootstrap/scaffolding.html(当你滚动subnav固定到那个主导航时)
有没有人实现过这个或有任何教程吗?
答案 0 :(得分:73)
以下是我实现此功能的代码:
$(document).scroll(function(){
// If has not activated (has no attribute "data-top"
if (!$('.subnav').attr('data-top')) {
// If already fixed, then do nothing
if ($('.subnav').hasClass('subnav-fixed')) return;
// Remember top position
var offset = $('.subnav').offset()
$('.subnav').attr('data-top', offset.top);
}
if ($('.subnav').attr('data-top') - $('.subnav').outerHeight() <= $(this).scrollTop())
$('.subnav').addClass('subnav-fixed');
else
$('.subnav').removeClass('subnav-fixed');
});
答案 1 :(得分:24)
截至2012-12-04,已接受的答案不再是最佳选择,因为所需功能已包含在Bootstrap中。 请参阅Affix JavaScript component,它是Bootstrap JS的一部分
答案 2 :(得分:12)
来自@Oleg的精彩回答,
对于像我这样想要重现.subnav
的响应行为的人这是css代码(没有颜色,边框和效果)
body { padding-top: 90px; }
@media (max-width: 980px) {
body {
padding-top: 0;
}
}
.subnav {
width: 100%;
}
@media (max-width: 768px) {
.subnav {
position: static;
top: auto;
z-index: auto;
width: auto;
height: auto;
}
.subnav .nav > li {
float: none;
}
}
@media (min-width: 980px) {
.subnav-fixed {
position: fixed;
top: 40px;
left: 0;
right: 0;
z-index: 1020;
}
.subnav-fixed .nav {
width: 938px;
margin: 0 auto;
}
}
@media (min-width: 1210px) {
.subnav-fixed .nav {
width: 1168px;
}
}
如果要克隆菜单的样式(包括颜色,边框和效果)
答案 3 :(得分:0)
上面的两个答案很有用,但我只是想让我知道我已经把它变成了ForbesLindesay/booting-sub-nav的模块(没有jQuery依赖)。它可以与脚本标记一起使用,也可以通过https://github.com/component/component/
使用答案 4 :(得分:0)
这是另一个代码
$(function(){
var
$win = $(window),
$filter = $('.navbar'),
$filterSpacer = $('<div />', {
"class": "filter-drop-spacer",
"height": $filter.outerHeight()
});
$win.scroll(function(){
if(!$filter.hasClass('navbar-fixed-top')){
if($win.scrollTop() > $filter.offset().top){
$filter.before($filterSpacer);
$filter.addClass("navbar-fixed-top");
}
}else if ($filter.hasClass('navbar-fixed-top')){
if($win.scrollTop() < $filterSpacer.offset().top){
$filter.removeClass("navbar-fixed-top");
$filterSpacer.remove();
}
}
});
});