滚动标题后,我的导航栏是否无法粘贴到顶部?

时间:2017-11-28 22:41:28

标签: jquery html css



$(document).ready(function() {
    $(window).scroll(function() {
        var distanceFromTop = $('#sticky_menue').scrollTop();
        if (distanceFromTop >= $('#header').height())
        {
            $('#sticky_menue').addClass('fixed');
        }
        else
        {
            $('#sticky_menue').removeClass('fixed');
        }
    });
});

#sticky.fixed {
    display: block;
    position: fixed;
    top: 0px;
    width: 100%;

<!-- Nav Bar -->
    <div id="sticky_menue">
     <div id="nav_bar">
      <div id="logo_nav"> Logo </div>
      <ul> 
        <li><a href="link">Home</a></li>
        <li><a href="link">Portfolio</a></li>
        <li><a href="link">Social</a></li>
        <li><a href="link">About</a></li>
        <li><a href="link">Contact</a></li>
      </ul>
      </div>
    </div>
&#13;
&#13;
&#13;

这是我的代码:https://jsfiddle.net/32atL9pc/

我在滚过标题后试图让导航栏坚持到顶部?

2 个答案:

答案 0 :(得分:0)

这是一个使用原生js的解决方案:

CSS添加和修改:

html, body {
    margin: 0;
    padding: 0;
}
* {
    box-sizing: border-box;
}
#sticky_menue {
    background: #fff;
    width: 100%;
    height: 60px;
}
#sticky_menue.normal{
    position:relative;
}
#sticky_menue.fixed {
    display: block;
    position: fixed;
    top: 0px;
}

JS:

window.addEventListener('scroll', function() {

    var contentDiv = document.getElementById('content_area');
    var navDiv = document.getElementById('sticky_menue');
    var navDivHeight = navDiv.offsetHeight;
    var distance = contentDiv.getBoundingClientRect().top;

    if (distance <= navDivHeight) {
        navDiv.classList.replace('normal', 'fixed');
    }
    else if (distance > navDivHeight) {
        navDiv.classList.replace('fixed', 'normal');
    }
});

<强> https://jsfiddle.net/32atL9pc/16/

答案 1 :(得分:0)

你的css为#sticky.fixed 提供了一个从未满足的课程。

尝试 .fixed #sticky_menue.fixed