我有一个页面,我希望在滚动后显示500px后我会使用"如果你想在滚动一些像素后显示一个div,没有jquery"来自apaul34208(show div after 800px scroll)的代码段。我改编的代码是这样的:
<!DOCTYPE html>
<html>
<body>
<div id="myID" class="pointer hide">
<img src="image.png">
</div>
<script>
myID = document.getElementById("myID");
var myScrollFunc = function () {
var y = window.scrollY;
if (y >= 400) {
myID.className = "pointer show"
} else {
myID.className = "pointer hide"
}
};
window.addEventListener("scroll", myScrollFunc);
</script>
</body>
</html>
和CSS:
.hide {
display: none;
}
.show {
display: block;
margin-top: -80px;
}
唯一的问题是我还希望它再次消失,让我们从页面底部说400 px。页面高度因页面而异,所以我不能设置像下面那样的范围400-1000像素。
<script>
myID = document.getElementById("myID");
var myScrollFunc = function () {
var y = window.scrollY;
if (y >= 400 & y <= 1000 ) {
myID.className = "pointer show"
} else {
myID.className = "pointer hide"
}
};
window.addEventListener("scroll", myScrollFunc);
</script>
</body>
</html>
任何人都知道如何才能实现这一目标?
谢谢你们!
答案 0 :(得分:1)
使用document.height
获取文档的高度并保留所需的值:
myID = document.getElementById("myID");
var myScrollFunc = function () {
var y = window.scrollY;
if (y >= 400 & y <= document.height - 400) {
myID.className = "pointer show";
} else {
myID.className = "pointer hide";
}
};
window.addEventListener("scroll", myScrollFunc);