對於工作,我必須在滾動時固定一個元素(例如向下滾動頁面會使元素自動調整自動以便始終可見)。我必須解決的問題是如何在不對高度值進行硬編碼的情況下進行此操作。有沒有辦法做到這一點?滾動沒有硬編碼值的元素jQuery
這裏是它的代碼:
// fix the orange box to the top after scrolling a certain amount
$(window).scroll(function(e){
var scrollTop = $(window).scrollTop();
// enforce a max based on current content length
if ($(this).scrollTop() >= ($('.mainContent2ColLayout250').height() - 400))
scrollTop = ($('.mainContent2ColLayout250').height() - 400);
if ($(this).scrollTop() >= 340)
$('.fixedElement').css({'marginTop': scrollTop - 325, 'marginBottom': -1 * (scrollTop - 325)});
if ($(this).scrollTop() < 340)
$('.fixedElement').css({'marginTop': 0, 'marginBottom': 0});
});
任何幫助,將不勝感激。
謝謝!
有沒有你不能只是設置元素的'position'到'fixed'任何理由? – Mogzol
@ user2101411目前尚不清楚你想如何保持元素可見。 'position:fixed'會使元素顯示在文檔中的正常位置,但固定元素不會影響其餘元素的佈局,也不會隨頁面一起滾動。還有其他選項,例如使用'position:absolute'將其設置爲特定的位置,例如左上角或其他位置,但我不確定您的問題描述中實際需要的是什麼。 – Zack
我被迫使用這個代碼,而不是做很簡單和容易的方式使用位置:固定和有jquery添加/刪除類或添加樣式.. – user2101411