頁面滾動到指定閾值時,目標元素固定在視口頂部(position: fixed),形成吸頂導航;向上滾動超過閾值恢復靜態定位。
// 控制吸頂顯示
function fixshow(min_height) {
min_height = min_height || 830; // 默認閾值
$(window).scroll(function() {
var scrollTop = $(window).scrollTop();
var $tab = $(".fixtabwrap");
var $tip = $("#proBuyTip");
if (scrollTop > min_height) {
$tip.fadeIn(100);
$tab.addClass("topfixed");
} else {
$tip.fadeOut(200);
$tab.removeClass("topfixed");
}
});
}
// 調用
$(function() { fixshow(830); });
.topfixed {
position: fixed !important;
top: 0;
left: 0;
z-index: 999;
width: 100%;
background-color: white;
/* IE6 兼容 hack */
_position: absolute;
_top: expression(eval(document.documentElement.scrollTop));
}
requestAnimationFrame 或 lodash.throttle 節流padding-top 補償element.offsetTop 而非硬編碼,適應響應式佈局const $tab = $('.fixtabwrap');
const threshold = $tab.offset().top;
let ticking = false;
$(window).on('scroll', () => {
if (!ticking) {
requestAnimationFrame(() => {
const stuck = $(window).scrollTop() > threshold;
$tab.toggleClass('topfixed', stuck);
$('#proBuyTip').toggle(stuck);
ticking = false;
});
ticking = true;
}
});
// CSS 佔位防跳動
.topfixed-placeholder { display: none; }
.topfixed + .topfixed-placeholder { display: block; height: 48px; /* 等於 tab 高度 */ }
此模式廣泛應用於電商詳情頁、文檔側邊欄、後台管理頂部導航等場景。