我有一個(gè)標(biāo)題浮動(dòng)框,當(dāng)你向下滾動(dòng)頁(yè)面時(shí)它就會(huì)消失。工作正常,只是在我的iPad上不行。
當(dāng)我向上滾動(dòng)頁(yè)面時(shí),導(dǎo)航菜單如期出現(xiàn),但當(dāng)我放開頁(yè)面時(shí),它又消失了。當(dāng)頁(yè)面到達(dá)底部時(shí),它也會(huì)出現(xiàn)
<!doctype html>
<html>
<head>
<title>Our Funky HTML Page</title>
<meta name="description" content="Our first page">
<meta name="keywords" content="html tutorial template">
<style>
.main-header {
width: 100%;
position: fixed;
top: 0;
background-color: #ffff00;
padding: 0.5rem 2.0rem 0.5rem 1.9rem;
height: 7.0rem;
z-index: 50;
display: flex;
margin: auto;
align-items: center;
justify-content: space-between;
transition: top 0.4s; /* Transition effect when sliding down (and up) */
}
.content {
width: 100%;
background-color: #ff0000;
height: 2000px;
}
</style>
<script>
var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
// if ( ( (prevScrollpos > currentScrollPos) || ( currentScrollPos < 50 ) ) ){
if ( ( (prevScrollpos >= currentScrollPos) ) ){
document.getElementById("main-header").style.top = "0rem";
} else {
document.getElementById("main-header").style.top = "-8rem"; // "-70px";
}
prevScrollpos = currentScrollPos;
}
</script>
</head>
<body>
<div class="main-header" id="main-header"></div>
<div class="content" ></div>
</body>
</html>
我在這個(gè)問題上已經(jīng)掙扎了一段時(shí)間,以下是我的發(fā)現(xiàn):
問題是,在iOS上,頁(yè)面在頂部和底部邊緣反彈,因此window . page yo offset值可能為負(fù)值,也可能大于實(shí)際頁(yè)面高度。因此,prevScrollpos & gt= currentScrollPos條件不充分。
一種解決方案是通過添加overscroll-behavior來禁用反彈效果:none轉(zhuǎn)換為html元素。
正確的解決方案是將條件擴(kuò)展到邊緣情況:
const maxScrollHeight = document.body.scrollHeight - window.innerHeight;
if (prevScrollpos >= currentScrollPos && currentScrollPos < maxScrollHeight) { // Prevent hiding header on bottom overscroll
document.getElementById("main-header").style.top = "0rem";
} else if (currentScrollPos > 0) { // Prevent hiding header on top overscroll
document.getElementById("main-header").style.top = "-8rem";
}