因此,我实质上是在尝试(以最粗略的方式)从该网站中提取标题。他们要做的是,当用户在> 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>
该类在向下滚动时适用,但在向上滚动时不适用。有任何想法吗?
这是这行的秘密:
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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句