電商商品頁常見的行為:往下捲過主圖之後,購買資訊列會浮出來並固定在視窗頂端,隨時都能下單。這個效果需要 jQuery。
監聽捲動事件,比對目前捲動距離與門檻值。超過就讓圖層淡入並加上固定定位的 class,未超過就淡出並移除該 class。
// 控制頭部購物車的顯示
function fixshow(min_height){
min_height ? min_height = min_height : min_height = 830;
$(window).scroll(function(){
var s = $(window).scrollTop();
if (s > min_height) {
$("#proBuyTip").fadeIn(100);
$(".fixtabwrap").addClass("topfixed");
} else {
$("#proBuyTip").fadeOut(200);
$(".fixtabwrap").removeClass("topfixed");
};
});
};
.topfixed {
position: fixed !important;
top: 0px;
left: 0px;
z-index: 999;
width: 100%;
background-color: white;
position: absolute;
_top: expression(eval(document.documentElement.scrollTop));
}
門檻值不要寫死。範例把 830 當預設值,但不同螢幕解析度、不同商品的主圖高度都不一樣。比較穩的做法是直接量測觸發點的位置:
var threshold = $("#proBuyTipTrigger").offset().top;
捲動事件要做節流。scroll 的觸發頻率非常高,每次都跑 fadeIn/fadeOut 會造成動畫堆疊。加上判斷避免重複觸發,效果會平順很多:
$(window).on("scroll", function(){
var s = $(window).scrollTop();
if (s > threshold) {
$("#proBuyTip").stop(true).fadeIn(100);
$(".fixtabwrap").addClass("topfixed");
} else {
$("#proBuyTip").stop(true).fadeOut(200);
$(".fixtabwrap").removeClass("topfixed");
}
});
position: fixed 之後又寫 position: absolute 是矛盾的。後者會被前者覆蓋,應該刪掉。_top: expression(...) 是給 IE6 的 hack,IE6 不支援 fixed 才需要這樣繞;現在已無維護價值,可以一併移除。
記得在 ready 時先呼叫一次。若使用者重新整理頁面時捲軸本來就在下方,只綁 scroll 事件的話工具列不會出現。補上一行 fixshow(); 即可。