首先先看一下影片演示:
其中的紅色框框,我們希望在卷軸往下拉、越過紅色框框時紅色框框能夠停留在上方,而卷軸往上拉回去時,紅色框框能夠回到原位。
這樣的效果常被用在網站的選單上面,讓使用者瀏覽網站時,能夠一直都看得到選單。
程式實現的邏輯是這樣的:
- 先取得紅色框框的位置。
- 當卷軸滑動時,計算卷軸是否滑超過等於卷軸的位置。
- 如果超過的話,固定紅色框框的位置,將其z-index提高,為了避免下面的元素補上來,先製作一個假的、但透明看不見的紅色框框再固定原紅色框框;否則,不固定紅色框框的位置。將假的紅色框框刪掉。
下面上程式碼:
1. html部份:
Other Content. Other Content. Other Content. Other Content. Other Content.</br> Other Content. Other Content. Other Content. Other Content. Other Content.</br> Other Content. Other Content. Other Content. Other Content. Other Content.</br> Other Content. Other Content. Other Content. Other Content. Other Content.</br> Other Content. Other Content. Other Content. Other Content. Other Content.</br> <div class="bar"> This is the div class, top_tab_bar_bg. </div> Other Content. Other Content. Other Content. Other Content. Other Content.</br> Other Content. Other Content. Other Content. Other Content. Other Content.</br> Other Content. Other Content. Other Content. Other Content. Other Content.</br> Other Content. Other Content. Other Content. Other Content. Other Content.</br> Other Content. Other Content. Other Content. Other Content. Other Content.</br>2. CSS部份:
body{
height : 1000px;
}
.bar{
width : 300px;
border-style:solid;
background-color: red;
}
//offset().top 是相對於文檔的偏移量,不會因為滾動卷軸而有變化。
//CSS裡的top屬性在position為fixed時,是對應到相對於所處螢幕的偏移量
//,會因滾動卷軸而有變化。
var barOffsetTop = $(".bar:not(.tempBar)").offset().top;
var barMarginTop = parseInt($(".bar:not(.tempBar)").css("margin-top"));
$(window).scroll(function() {
var scrollTopAmount= $(this).scrollTop();
//因為bar的position被設成fixed時會使下面的元素跑上來,所以做一個透明的tempBar來填充原來
//bar的位置
if (scrollTopAmount >= barOffsetTop){
//如果卷軸拉超過bar的原始offset.top(),將bar固定住
//如果沒有tempBar,做一個tempBar
if ($(".tempBar").length == 0){
$(".bar").clone().addClass('tempBar').insertAfter(".bar").css({"opacity":"0","z-index":"auto"});
}
$(".bar:not(.tempBar)").css({ "position": "fixed", "top": "-"+barMarginTop+"px" , "z-index" : "999"});
}else{
//如果卷軸拉沒有超過bar的原始offset.top(),將bar的css還原,刪除tempBar
$(".tempBar").remove();
$(".bar:not(.tempBar)").css({ "position": "static" , "z-index" : "auto"});
}
});
線上看成品:
http://jsfiddle.net/a33e97cg/
沒有留言 :
張貼留言