我有一个导航栏在一个网页我正在工作。 我添加了一些jquery代码,以便在用户向下滚动时显示导航栏。 这样做的问题是,有一些页面的整个高度是如此之小,以至于用户将无法向下滚动。 在这种情况下,导航栏永远不会显示,因为不可能滚动。
如何更改代码,以便在没有滚动的情况下默认显示导航栏?
下面是当用户滚动时显示导航栏的jquery代码
<script type="text/javascript">
window.onscroll = function() {
scrollFunction()
};
function scrollFunction() {
if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) {
document.getElementById("navbar").style.top = "0";
} else {
document.getElementById("navbar").style.top = "-100px";
}
}
</script>
我认为最好的方法是将文档高度与窗口高度进行比较,以了解文档是否在浏览器的窗口高度内。 所以我会写这样的东西:
<script type="text/javascript">
var body = document.body,
html = document.documentElement;
var documentHeight = Math.max( body.scrollHeight, body.offsetHeight,
html.clientHeight, html.scrollHeight, html.offsetHeight );
if (documentHeight <= window.innerHeight) {
document.getElementById("navbar").style.top = "0";
} else {
window.onscroll = function() {
scrollFunction()
};
function scrollFunction() {
if (document.body.scrollTop > 80 || document.documentElement.scrollTop > 80) {
document.getElementById("navbar").style.top = "0";
} else {
document.getElementById("navbar").style.top = "-100px";
}
}
}
</script>
在vanilla JS中,文档高度计算有点混乱,如果你想的话,你可以把它放在一个函数中,让它更干净。