我不能让我的导航更改滚动

时间:2015-04-23 04:25:19

标签: javascript jquery css

我知道这是一个重复的问题,但是我试图让我的导航栏使用JavaScript / jQuery / CSS来改变样式,使jQuery根据滚动条的位置添加和删除类,但没有优势。我是jQuery的巨大菜鸟。有人能告诉我这些代码是否有问题。我搜索了几个小时,我找不到和错误。这是一个有效的例子:http://codepen.io/anon/pen/QbWOJv 这是我的代码:

// on scroll, 
$(window).on('scroll',function(){

    // we round here to reduce a little workload
    stop = Math.round($(window).scrollTop());
    if (stop > 50) {
        $('.nav').addClass('passed-main');
    } else {
        $('.nav').removeClass('passed-main');
    }
.nav
            {
                background-color: #000000;
                opacity: 0.3;
                width: 100%;
                height: 40px;
                position: fixed;
                top: 0;
                z-index: 2000;
                transition: all 0.3s;
            }
            .nav.past-main
            {
                background-color: #ffffff;
                opacity: 1;
            }
<div class="nav">
        </div>

1 个答案:

答案 0 :(得分:1)

也许这个例子是你想要实现的,当你尝试使用上面的代码时,它就无法正常工作。

以下是代码在代码段中的问题:

  1. 您忘了关闭功能

    // on scroll, 
    $(window).on('scroll',function(){    
        // we round here to reduce a little workload
        stop = Math.round($(window).scrollTop());
        if (stop > 50) {
            $('.nav').addClass('passed-main');
        } else {
            $('.nav').removeClass('passed-main');
        }
    }); // You forgot to close the function here
    
  2. 您在passed-main使用班级选择器CSS

  3. 时添加/删除班级.nav.past-main
  4. 您的窗口没有任何滚动条,因此您需要将其添加到CSS以测试其是否有效

    body {
        height: 1500px;
    }
    
  5. 您忘记在代码段中添加jQuery

  6. 这是工作更新的代码段

    // on scroll, 
    $(window).on('scroll', function () {
    
        // we round here to reduce a little workload
        stop = Math.round($(window).scrollTop());
        if (stop > 50) {
            $('.nav').addClass('past-main');
        } else {
            $('.nav').removeClass('past-main');
        }
    });
    .nav {
        background-color: #000000;
        opacity: 0.3;
        width: 100%;
        height: 40px;
        position: fixed;
        top: 0;
        z-index: 2000;
        transition: all 0.3s;
    }
    .nav.past-main {
        background-color: #ffffff;
        opacity: 1;
    }
    body {
        height: 1500px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <div class="nav"></div>

相关问题