一、利用position的sticky屬性
sticky
頁面不動的情況下,它就像 position:relative;
而當頁面滾動超出目標區域時,它表現的就像 position:fixed;,會固定在目標位置。
relative(相對定位)是指給元素設置相對於原本位置的定位,元素並不脫離文檔流,因此元素原本的位置會被保留,其他的元素位置也不會受到影響。
而fixed:表示固定定位,與absolute定位類型類似,但它的相對移動的坐標並不是body,而是視圖(屏幕內的網頁窗口)本身
#sticky-nav { position: sticky; top: 0px; /**必須設置一個top值,否則不生效 */ width: 100%; height: 80px; background-color: yellowgreen;
}
但是瀏覽器兼容性不好
所以采取所以采取第二種方法
二、通過監聽瀏覽器scroll事件,動態綁定class
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style> * { margin: 0; padding: 0 } html body { height: 100vh; width: 100% } h1 { height: 200px; position: relative; background-color: lightblue;
} h1:after { content: ''; position: absolute; top: 100px; left: 0; width: 100%; height: 2px; background-color: red;
} #sticky-nav {
/* position: sticky; */ top: 0px; /**必須設置一個top值,否則不生效 */ width: 100%; height: 80px; background-color: yellowgreen;
} .scroll-container { height: 600px; width: 100%; background-color: lightgrey;
} .fiexd { position: fixed; top: 0;
}
</style>
</head>
<body>
<h1>高200px;距頂部100px</h1>
<div id="sticky-nav">這是一個tab切換欄,給sticky定位top=100px</div>
<p class="scroll-container">發生滾動</p>
<p class="scroll-container" style="background:lightgoldenrodyellow;">發生滾動</p>
</body>
<script> window.onscroll = function(){ var scrollT = document.documentElement.scrollTop||document.body.scrollTop; var scrollH = document.documentElement.scrollHeight||document.body.scrollHeight; var clientH = document.documentElement.clientHeight||document.body.clientHeight console.log('scrollT:'+scrollT) console.log('scrollH:'+scrollH) console.log('clientH:'+clientH) if(scrollT>200){ console.log("滾輪已經大於200,置頂按鈕出現"); document.getElementById('sticky-nav').classList.add('fiexd') //動態綁定class屬性
}else { document.getElementById('sticky-nav').classList.remove('fiexd') //動態刪除class屬性
} } </script>
</html>