一旦用户滚动到stickyDiv
的顶部,我便将容器stickInDiv
的位置固定在视口的底部,直到它的原始位置(我从文档顶部计算出)为止视口的底部。之后,容器应保持在其原始位置。向上滚动时,一旦其原始位置到达视口底部,它应该再次固定在视口底部。
当前行为:stickyDiv
不会在视口底部到达其原始位置时停留在其原始位置。
window.onscroll = function() {
scrollFunction();
};
function getTop(elem) {
const box = elem.getBoundingClientRect();
const body = document.body;
const docEl = document.documentElement;
const scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
const clientTop = docEl.clientTop || body.clientTop || 0;
const top = box.top + scrollTop - clientTop;
return Math.round(top)
}
const stickyDiv = document.getElementById('stickyDiv');
const stickyElemTopFromDocumentTop = getTop(stickyDiv);
const Height = stickyDiv.clientHeight; /* height of the sticky element */
const stickInDiv = document.getElementById('stickInDiv');
const stickInDivOffsetTop = stickInDiv.offsetTop;
function scrollFunction() {
if (window.pageYOffset > stickyElemTopFromDocumentTop) {
stickyDiv.classList.remove('sticky');
} else if (window.pageYOffset > stickInDivOffsetTop) {
stickyDiv.classList.add('sticky');
} else {
stickyDiv.classList.remove('sticky');
}
}
#contentAtTop {
height: 100px;
background-color: blue;
opacity: 0.2;
color: white;
}
#contentBeforeStickyDiv {
height: 1200px;
background-color: green;
color: white;
opacity: 0.8;
}
#stickyDiv {
color: white;
background-color: grey;
height: 40px;
}
#contentAfterStickyDiv {
height: 400px;
background-color: purple;
color: white;
opacity: 0.8;
}
.sticky {
position: fixed;
bottom: 0;
width: 100%;
}
<body>
<div id="contentAtTop">Content At Top</div>
<div id="stickInDiv">
<div id="contentBeforeStickyDiv">Content Before Sticky Div</div>
<div id="stickyDiv">Sticky Container</div>
<div id="contentAfterStickyDiv">Content After Sticky Div</div>
</div>
</body>