Javascript 固定菜单位置的 Scrolltop

Javascript Scrolltop for fixed menu position

我想在 javascript 中滚动几个像素后保留我的菜单栏,但它无法正常工作。这是我的脚本。

JavaScript代码:

window.onscroll = function() {stick()};

function stick() {
    if (document.body.scrollTop || document.documentElement.scrollTop > 150) {
        document.getElementById("test").style.position = "fixed";
        document.getElementById("test").style.background = "blue";
    } else {
        document.getElementById("test").style.position = "initial";
    }
}

问题:
每当我滚动一个像素时,我的测试 ID 都会得到修复。我试图在 if 中更改 scrollTop 值,但没有任何效果。如有关注,我们将不胜感激。

更新: 这里也是使用ids的错误。

<script>
document.getElementById("cntnr").onscroll = function() {stick()};

function stick() {
    if (document.getElementById("cntnr").scrollTop > 119) {
    document.getElementById("navdwn").style.position = "fixed";
    } else {
    document.getElementById("navdwn").style.position = "initial";
    }
}
</script>

试试这个代码,你需要 javascript 的 parseInt() 函数来使 document.documentElement.scrollTop等于整数

window.onscroll = function() {stick()};

var offset = document.documentElement.scrollTop

function stick() {
    if (parseInt(offset) > 150) {
       document.getElementById("test").style.position = "fixed";
       document.getElementById("test").style.background = "blue";
    } else {
       document.getElementById("test").style.position = "initial";
    }
}

验证您的 If 条件,修复菜单当前文档滚动到顶部 150px

变化:

window.onscroll = function() {stick()};

function stick() {
if (document.body.scrollTop > 150 ) {
    document.getElementById("test").style.position = "fixed";
    document.getElementById("test").style.background = "blue";
} else {
    document.getElementById("test").style.position = "initial";
}
}

一旦开始滚动,document.body.scrollTop 的值将大于 0。如果第一个条件为真 ,OR 运算符 将不会检查第二个条件。

因此,一旦您开始滚动,第一个条件就会变为真,然后测试 ID 就会得到修复。

将条件更改为 if (document.body.scrollTop > 150 ) {.... 即可。