结合粘性导航和过渡

时间:2015-09-01 13:11:52

标签: javascript jquery html css twitter-bootstrap

我有一个使用Bootstrap导航的Wordpress网站。我的徽标/品牌下方有导航。我想要导航'坚持'当用户滚动到屏幕顶部时到屏幕顶部。一旦导航被卡住了#39;到顶部我希望它的高度可以更大的动画。

我有单独的工作代码,但不知道如何将它们组合起来以达到我想要的目的。

HTML - 缩放导航

<script>
 $(function(){
 var shrinkHeader = 25;
 $(window).scroll(function() {
 var scroll = getCurrentScroll();
  if ( scroll >= shrinkHeader ) {
       $('header').addClass('shrink');
    }
    else {
        $('header').removeClass('shrink');
    }
 });

  function getCurrentScroll() {
    return window.pageYOffset || document.documentElement.scrollTop;
  }
  });
</script>

HTML - 粘性脚本

<script>
$(document).ready(function() {
var s = $("#divname");
var pos = s.position();                    
$(window).scroll(function() {
    var windowpos = $(window).scrollTop();
    if (windowpos >= pos.top) {
        s.addClass("stick");
    } else {
        s.removeClass("stick"); 
    }
});
});
</script>

HTML - header.php

    

    <a class="brand" href="<?php echo home_url(); ?>/"></a>

    <div class="navbar-header">
        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> 
            <span class="sr-only">Toggle navigation</span> 
            <span class="icon-bar"></span> 
            <span class="icon-bar"></span> 
            <span class="icon-bar"></span> 
        </button> 

    </div>  

    <div class="navbar-collapse collapse">

...

CSS

header {
 position: fixed;
 overflow: hidden;
 z-index: 100;
 width: 100%;
 top: 0; left: 0;
 padding: 0 25px;
 text-align: center;
 background-color: rgba(250,250,250,1);
 -webkit-transition: height 0.35s ease, padding 0.35s ease;
 -moz-transition: height 0.35s ease, padding 0.35s ease;
 -ms-transition: height 0.35s ease, padding 0.35s ease;
 -o-transition: height 0.35s ease, padding 0.35s ease;
 transition: height 0.35s ease, padding 0.35s ease;
}

1 个答案:

答案 0 :(得分:0)

要完成此结果非常简单,您需要查看.navbar-fixed-top。 Bootstrap使这个类的导航栏变得粘稠。这是一个例子:

JS:

clearSearch()

CSS:

$(document).ready(function() {
    $(window).scroll(function() {
        var windowpos = $(window).scrollTop();
        var navbar = $('#navbar');

        // if win >= navbar and not already a sticky
        if (windowpos >= navbar.position().top && !navbar.hasClass("navbar-fixed-top") ) {
            navbar.addClass("navbar-fixed-top");

        // if win <= navbar and is a sticky
        } else if( windowpos <= navbar.position().top && navbar.hasClass("navbar-fixed-top")  ) {
            navbar.removeClass("navbar-fixed-top");
        }
    });
});

这增加了填充,但是当设置#navbar { background-color:orange; padding:5px; transition: all 0.35s ease; } #navbar.navbar-fixed-top { position: fixed; top:0; left:0; right:0; padding: 20px; transition: all 0.35s ease; } 时,任何css变量都可以。这是没有bootstrap的示例jsfiddle