所以,我本质上是在尝试从 this website 中提取(以尽可能粗略的方式) header 。 。他们所做的是,当用户滚动到> 0 的位置时,他们添加一个额外的类。我认为这很简单,但 java 总是有办法给我带来问题。我想出了以下代码:
<!DOCTYPE html>
<html>
<head>
</head>
<style>
body {
height: 5000px;
}
#scroll {
position: fixed;
height: 50px;
width: 100%;
}
.box {
background-color: orange;
color: white
}
.test {
background-color: red;
color: pink;
}
</style>
<script>
window.onscroll = function() {
myFunction();
};
function myFunction() {
if (document.body.scrollTop > 0 || document.documentElement.scrollTop > 0) {
document.getElementById("scroll").className = "test";
} else {
document.getElementById("scroll").className = "";
}
}
</script>
<body>
<div class="box" id="scroll">THIS ISNT WORKING</div>
</body>
</html>
当我向下滚动时,该类适用,但当我向上滚动时,该类不适用。有什么想法吗?
最佳答案
这是 secret ,在这一行:
document.getElementById("scroll").className = "";
您没有将其设置回旧的类box
,因此当滚动回顶部时它没有类。像这样更改它:
function myFunction() {
if (document.body.scrollTop > 0 || document.documentElement.scrollTop > 0) {
document.getElementById("scroll").className = "test";
} else {
document.getElementById("scroll").className = "box";
}
}
演示:
<!DOCTYPE html>
<html>
<head>
</head>
<style>
body {
height: 5000px;
}
#scroll {
position: fixed;
height: 50px;
width: 100%;
}
.box {
background-color: orange;
color: white
}
.test {
background-color: red;
color: pink;
}
</style>
<script>
window.onscroll = function() {
myFunction();
};
function myFunction() {
if (document.body.scrollTop > 0 || document.documentElement.scrollTop > 0) {
document.getElementById("scroll").className = "test";
} else {
document.getElementById("scroll").className = "box";
}
}
</script>
<body>
<div class="box" id="scroll">THIS ISNT WORKING</div>
</body>
</html>
关于javascript - 在滚动上添加类不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34843712/