作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图防止滚动元素重叠到网站的页脚中。我已经把它放在页面顶部的某个元素上不重叠但它仍然重叠在页脚上的地方。
这是我目前的代码:
// fix the orange box to the top after scrolling a certain amount
$(window).scroll(function() {
// get the scroll position top
var window_pos = $(window).scrollTop();
// fix the element on scroll
if (window_pos >= $('#sticky').offset().top) {
$('#suggestions').attr('style', 'position: fixed; top: 0px;');
// prevent overlapping into the footer
if (window_pos >= $('#sticky2').offset().top || window_pos >= $('.footer').offset().top) {
alert("exceeded");
$('#suggestions').attr('style', 'position: absolute');
} else {
// restore fixed position
if ($(document).scrollTop() + window.innerHeight < $('#sticky2').offset().top) {
$('#suggestions').attr('style', 'position: fixed; top: 0px;');
}
}
} else if (window_pos < $('#sticky').offset().top - 20) {
$('#suggestions').attr('style', 'position: absolute');
}
});
和两个div元素如下:
<div id="sticky" style="height: 20px; margin-top: 5px; visibility: hidden;"></div>
<div id="sticky2" style="height: 50px; margin-top: 10px; visibility: hidden;"></div>
如有任何帮助,我们将不胜感激。
谢谢!
最佳答案
试试这个
$(window).scroll(function() {
// get the scroll position top
var window_pos = $(window).scrollTop();
// fix the element on scroll
if (window_pos >= $('#sticky').offset().top) {
$('#suggestions').css({
'position': 'fixed',
'top': '0px'
});
// prevent overlapping into the footer
if (window_pos >= $('#sticky2').offset().top || window_pos >= $('.footer').offset().top) {
$('#suggestions').css({
'position': 'static',
'top': 'auto'
});
} else {
// restore fixed position
if ($(document).scrollTop() + window.innerHeight < $('#sticky2').offset().top) {
$('#suggestions').css({
'position': 'fixed',
'top': '0px'
});
}
}
} else if (window_pos < $('#sticky').offset().top - 20) {
$('#suggestions').css({
'position': 'static',
'top': 'auto'
});
}
});
关于jquery - 固定元素重叠到页脚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40218687/
我是一名优秀的程序员,十分优秀!