固定元素离开默认位置后更改样式

时间:2013-03-29 19:42:50

标签: jquery css

我正在开发一个应该有固定导航菜单的网站,所以它会随你滚动。我遇到的唯一问题是设计师想要这样做,一旦导航器离开它的位置并开始向下滚动页面,它会在顶部拾取一个厚黑色边框。一旦它开始移动,有没有办法添加样式?

现有代码:

<ul id="stickyNav">
<li class="technology"><a href="#technology">Technology</a></li>
      <li class="sales"><a href="#sales">Sales</a></li>
      <li class="operations"><a href="#operations">Operations</a></li>
      <li class="marketing"><a href="#marketing">Marketing</a></li>
      <li class="profitability"><a href="#profitability">Profitability</a></li>
</ul>

ul#stickyNav{background: url(../../../images/bb/stickynav-bg.jpg) repeat-x; height: 56px; position: fixed; width: 100%; z-index: 800;}

2 个答案:

答案 0 :(得分:1)

你可以先找一些样本,你可以查看this fiddle以查看它的实际效果!

请注意,我必须克隆导航而不是弄乱实际的DOM。如果导航有很多交互,则可以在开始滚动时使用visibility: hidden

祝你好运!

CSS

#body {
    position: relative;
    top: 0;
}
#content {
    height: 2000px;
}
.nav {
    width: 100%;
    background: black;
    color: white;
}

HTML

<div id="body">
    <h1>Stuff</h1>
    <div id="nav" class="nav">Scroll on the go!</div>
    <div id="content">Interestring things</div>
</div>

的jQuery

$(function() {
    var $nav = $("#nav");
    $nav.get(0).originalY = $nav.offset().top;
});
$(document).scroll(function() {
    var $nav = $("#nav");
    var navDOM = $nav.get(0);
    var curY = $(document).scrollTop();

    // Check whether it started scrolling after the navbar
    if (curY > navDOM.originalY) {
        if ($('#nav_clone').length < 1) {
            // Note that you only have to clone the navigation once per scroll event
            $nav.clone()
                .attr('id', 'nav_clone')
                .addClass('nav')
                .css('position', 'fixed')
                .css('top', 0)
                .appendTo("#body");
        }
    }
    // Else, we remove the cloned navigation
    else {
        $('#nav_clone').remove();
    }
});

编辑:请注意,您可以使用适当的ID #nav#nav_clone添加自定义CSS样式以滚动导航栏或原始样式。 .nav让你分享共同的风格。

答案 1 :(得分:0)

我没有试过blint的代码,所以也可能有用,但是其他人给了我一个更简单的解决方案:

sticky = $('#stickyNav');
classtoAdd = 'nav_active';

$(window).scroll(function(){
/* Sticky Nav stuff */
var window_top = $(window).scrollTop();
if(window_top > 0){
sticky.addClass(classtoAdd);


}else{
sticky.removeClass(classtoAdd);

}
/* End Sticky Nav */


}); 

然后我在CSS中添加了任何新样式为#stickyNav.nav_active {}