固定菜单位置的Javascript Scrolltop

Javascript Scrolltop for fixed menu position

本文关键字:Javascript Scrolltop 位置 菜单      更新时间:2023-09-26

我想在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值,但没有任何效果。如有任何关注,我们将不胜感激。

更新:这里还有使用id的错误。

<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>

验证您的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。如果第一个条件为true,则OR运算符不会检查第二个条件

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

将条件更改为if (document.body.scrollTop > 150 ) {....,它将起作用。

尝试一下这段代码,您需要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";
    }
}