[英]Offset fixed div from top and bottom
我的頁面右側有一個固定的 div。 我將它設置為隨頁面滾動而不與頁腳重疊,效果很好。 問題是它在向上滾動時與導航重疊。 有沒有辦法讓它對兩者都有效? 我試圖創建一個新的 function
function checkOffset() {
var a = $(document).scrollTop() + window.innerHeight;
var b = $('#footer').offset().top;
if (a < b) {
$('#social-float').css('bottom', '10px');
} else {
$('#social-float').css('bottom', (10 + (a - b)) + 'px');
}
}
$(document).ready(checkOffset);
$(document).scroll(checkOffset);
<nav class="nav">Nav Sample</nav>
<div id="social-float">
<div class="sf-twitter">twitter</div>
<div class="sf-facebook">facebook</div>
</div>
<div id="footer">footer sample</div>
在這里檢查這個小提琴的解決方案。 我在頁面上添加了調試文本,並且還考慮了導航欄可能由於頂部的其他 div 而偏移的事實。
/** * This function checks for both top and bottom edges to position itself * on the page */ function checkOffset() { var documentTop = $(document).scrollTop(); var currentScrollOffset = documentTop + window.innerHeight; var footerOffset = $('#footer').offset().top; var navbarEffectiveHeight = $('.nav').outerHeight() + $('.nav').offset().top; var $fixedElem = $('#social-float'); var fixedElemHeight = $fixedElem.outerHeight(); // until page scroll crosses navbar bottom edge (offset) if (currentScrollOffset < navbarEffectiveHeight) { $fixedElem.css('top', (currentScrollOffset + 10) + 'px'); $fixedElem.css('bottom', 'unset'); // page scroll crossed navbar bottom edge but not to extend of the height of fixed div // including the top and bottom spacing for it which is 20px } else if (currentScrollOffset < navbarEffectiveHeight + fixedElemHeight + 20) { $fixedElem.css('top', (window.innerHeight - (currentScrollOffset - navbarEffectiveHeight) + 10) + 'px'); $fixedElem.css('bottom', 'unset'); // page scroll hasn't crossed footer top edge (offset) } else if (currentScrollOffset < footerOffset) { $fixedElem.css('bottom', '10px'); $fixedElem.css('top', 'unset'); // page scroll crossed footer top edge (offset) } else { $fixedElem.css('bottom', (10 + (currentScrollOffset - footerOffset)) + 'px'); $fixedElem.css('top', 'unset'); } } $(document).ready(checkOffset); $(document).scroll(checkOffset);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.