固定div向下滚动&向上滚动时设置绝对值

时间:2016-01-23 08:25:14

标签: javascript

先生我想在向下滚动窗口时锁定我的菜单,其中div id menu固定在窗口顶部,而且我想在向上滚动时将位置设置为绝对我尝试使用此代码。它正确地完成了第一份工作。我可以将菜单设置在页面顶部。但在向上滚动时,它无法设置页面绝对位置是我的代码

  <script type="application/javascript">
    $(window).bind('scroll', function () {
        if (window.scrollY=100){
            document.getElementById("menu").style.position = "fixed";
            document.getElementById("menu").style.top = "0px";
            }
        else if(window.scrollY < 100){
            document.getElementById("menu").style.position = "absolute";
            document.getElementById("menu").style.top = "100px";
            }
    });

    </script>

1 个答案:

答案 0 :(得分:0)

您分配的是值而非比较window.scrollY=100 代码应该是:

$(window).bind('scroll', function () {
    if (window.scrollY>=100){
        //            ^^-----------use >= here
        document.getElementById("menu").style.position = "fixed";
        document.getElementById("menu").style.top = "0px";
        }
    else if(window.scrollY < 100){
        document.getElementById("menu").style.position = "absolute";
        document.getElementById("menu").style.top = "100px";
        }
});