[英]css/jquery scroll-fixed div issues
I'm trying to fix a div after a certain pixels when the window's browser scrolls down and after, when the window scrolls up, put the div in the same position at the beginning. 当窗口的浏览器向下滚动时,我试图在某个像素之后修复一个div,之后,当窗口向上滚动时,将div放在开头的相同位置。
$(window).scroll(function () {
var button = $('.button-mobile');
offset = button.offset().top;
position = button.position().top;
console.log(position);
if ($(this).scrollTop() >= offset) {
$('.button-mobile').css({
"max-height": "100%",
"position": "fixed",
"overflow-y": "auto",
"top": "40px",
"z-index": "1"
});
} else {
$('.button-mobile').css({
"position": "absolute",
"top": "none",
"overflow-y": "none",
"z-index": "none"
});
}
});
The if
branch works well. if
分支运行良好。 The else
branch is the problem, I think. 我认为,
else
分支是问题所在。
This branch is a test for a precedent experiment. 该分支是对先前实验的测试。
else
branch works with known height in px but not with the offset that change frequently. else
分支在px中以已知高度工作,但不与频繁更改的偏移一起工作。
Also I don't know why when the window scroll down to the div the position's top value is set to 40px. 另外我不知道为什么当窗口向下滚动到div时,位置的最高值设置为40px。
Thanks 谢谢
I suppose you should move button and offset assignment out of scroll callback: 我想你应该将滚动回调中的按钮和偏移量分配移出:
var button = $('.button-mobile');
var offset = button.offset().top;
$(window).scroll(function () {
position = button.position().top;
console.log(position);
if ($(this).scrollTop() >= offset) {
$('.button-mobile').css({
"max-height": "100%",
"position": "fixed",
"overflow-y": "auto",
"top": "40px",
"z-index": "1"
});
} else {
$('.button-mobile').css({
"position": "static",
"top": "none",
"overflow-y": "none",
"z-index": "none"
});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.