滚动时设置Bootstrap导航栏的透明度

15
我使用一个名为custom.css的辅助文件来覆盖bootstrap代码,我想知道如何创建一个仅当我的网站访问者不在页面顶部时才激活的代码。目前为止,我使用bootstrap提供的默认代码创建了一个透明的导航栏。唯一需要做的就是将它设置为在访问者向下滚动时执行:background-color: #color。例如:https://www.lyft.com/。当我在页面顶部时,导航栏是透明的,但当我向下滚动时,它变得不透明。

欢迎来到SO!:) 你目前尝试了什么?能否发布你的代码?我相信Lyft使用JavaScript来实现那种效果。 - David Passmore
我复制了原始的 .navbar-default bootstrap(如果需要,我可以提供给你),并修改了颜色。在 HTML 中,我将栏设置为顶部固定(使用 navbar-fixed-top)。除了搜索可能有用的东西之外,我什么也没做...我会研究 Lyft,也许我会找到一些有用的东西。编辑:当我使用“研究 Lyft”时,我是指查看他们的 CSS。 - Hiperkie
Lyft使用angular-js,并在用户向下滚动页面到达某个特定点时向导航栏添加.opaque类。 - David Passmore
谢谢!我会研究一下并尝试学习如何使用它 :) - Hiperkie
3个回答

39

要实现此效果,您需要以下代码:(我将使用jQuery,因为它是Bootstrap支持的语言)。


jQuery:

/**
 * Listen to scroll to change header opacity class
 */
function checkScroll(){
    var startY = $('.navbar').height() * 2; //The point where the navbar changes in px

    if($(window).scrollTop() > startY){
        $('.navbar').addClass("scrolled");
    }else{
        $('.navbar').removeClass("scrolled");
    }
}

if($('.navbar').length > 0){
    $(window).on("scroll load resize", function(){
        checkScroll();
    });
}

您也可以使用ScrollSpy来实现此目的。


以及您的CSS(示例):

/* Add the below transitions to allow a smooth color change similar to lyft */
.navbar {
    -webkit-transition: all 0.6s ease-out;
    -moz-transition: all 0.6s ease-out;
    -o-transition: all 0.6s ease-out;
    -ms-transition: all 0.6s ease-out;
    transition: all 0.6s ease-out;
}

.navbar.scrolled {
    background: rgb(68, 68, 68); /* IE */
    background: rgba(0, 0, 0, 0.78); /* NON-IE */
}

我无法启动它。我认为是因为该栏已经固定在顶部。我将修改脚本以监视另一个类。我认为这将解决问题。 - Hiperkie
在 Blazor 项目中使用 Bootstrap 4,效果非常流畅。 - Antonio Correia

0
为避免使用滚动、加载和调整大小事件所带来的性能损耗,现在可使用Intersection Observer API。它将允许您检测页面上的内容是否已经滚动,并相应地设置导航栏透明度(通过添加或删除类)。请查看此answer以获取更多详细信息。

0
$(document).ready(function() {
    $(window).scroll(function() {
       if($(this).scrollTop() > height) { 
           $('.navbar').addClass('scrolled');
       } else {
           $('.navbar').removeClass('scrolled');
       }
    });
});

1
你能详细说明一下这如何解决问题吗?你的代码可能是正确的,但你需要配以清晰的解释。 - maazadeeb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接