我在页面右侧有一个固定的div。我将其设置为可与页面一起滚动而不与页脚重叠,并且效果很好。问题是向上滚动时它与导航重叠。有什么办法可以使两者都起作用吗?我试图创建一个新功能
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>
答案 0 :(得分:1)
Here查看此小提琴以寻找解决方案。 我在页面上添加了调试文本,并且还考虑了导航栏可能由于顶部的其他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);