體驗效果:https://hovertree.com/texiao/jquery/12.htm
長頁面右側的侧欄(例如目錄、廣告)通常希望「滾到頂端就固定住」,但直接寫 position:fixed 會有兩個問題:一是元素會在最開始就固定在視窗上,二是滾到容器底部時不會跟著離開。以下用 scroll 事件解決。
$(document).ready(function(e) {
t = $('.hvtfixed').offset().top; // 固定元素原本的位置
mh = $('.mainhovertree').height(); // 左欄(參照容器)高度
fh = $('.hvtfixed').height(); // 固定元素自身高度
...
});
$(window).scroll(function(e){
s = $(document).scrollTop(); // 目前捲動距離
if (s > t - 10) {
$('.hvtfixed').css('position','fixed');
if (s + fh > mh) { // 已經接近容器底部
$('.hvtfixed').css('top', mh - s - fh + 'px');
}
} else {
$('.hvtfixed').css('position','');
}
});
邏輯分兩層:當捲動距離超過元素原本位置(t - 10 的 10 是預留的頂部間距),就切換成 fixed 定位;再進一步檢查「已捲距離 + 元素高度」是否超過容器高度,若是則把 top 改成負值,讓元素被視窗上緣「推」出畫面,不會壓到底部內容。回到頂端時則把 position 重設為空字串,還原成原本的靜態定位。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>滾動頁面時div到達頂部固定- 何問起</title>
<meta charset="utf-8" />
<style type="text/css">
* { padding: 0px; margin: 0px; color:white }
a { color:white }
.box { width: 1000px; background: #ccc; margin: 0 auto; overflow: hidden; }
.mainhovertree { width: 770px; height: 3000px; background: #000; float: left; }
.sub { width: 220px; background: #FC6; float: right; }
.sub01 { width: 220px; height: 100px; background: #0CC; margin-bottom: 10px; }
.hvtfixed {
width: 220px; height: 300px; background: #F66;
font: normal 13px/30px \5FAE\8F6F\96C5\9ED1;
text-align: center; top: 10px;
}
</style>
<script type="text/javascript" src="https://hovertree.com/ziyuan/jquery/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
t = $('.hvtfixed').offset().top;
mh = $('.mainhovertree').height();
fh = $('.hvtfixed').height();
$(window).scroll(function(e){
s = $(document).scrollTop();
if(s > t - 10){
$('.hvtfixed').css('position','fixed');
if(s + fh > mh){
$('.hvtfixed').css('top',mh-s-fh+'px');
}
}else{
$('.hvtfixed').css('position','');
}
})
});
</script>
</head>
<body>
<div class="box">
<div class="mainhovertree">
<div style="background-color:#959822; width:100%;height:150px;">請滾動頁面體驗效果</div>
<div style="background-color:Green; width:100%;height:150px;"><h3>滾動頁面時div到達頂部固定</h3></div>
<div style="background-color:Red; width:100%;height:150px;">歡迎</div>
<div style="background-color:Yellow; width:100%;height:150px;">首頁</div>
<div style="background-color:Olive; width:100%;height:350px;">何問起 滾動頁面</div>
<div style="height:130px;"></div>
</div>
<div class="sub">
<div class="sub01"></div>
<div class="sub01"></div>
<div class="hvtfixed">我是固定的喲</div>
</div>
</div>
</body>
</html>