应用场景:侧边栏需要在网页中fixed定位,但是也不能被底部遮住,即,如果滚动到
底部出现时,要保证侧边栏不被底部遮住,底部也不能被侧边栏遮住。
实现方法:如果底部出现,判断是否遮住侧边栏,如果没有遮住,侧边栏不动,如果即将遮住,侧边栏随着底部滚动而向上动,以达到效果
if (process.client) { //nuxt需要这个判断
function getScrollTop() {
let scrollTop = 0;
let bodyScrollTop = 0;
let documentScrollTop = 0;
if (document.body) {
bodyScrollTop = document.body.scrollTop;
}
if (document.documentElement) {
documentScrollTop = document.documentElement.scrollTop;
}
scrollTop =
bodyScrollTop - documentScrollTop > 0 ? bodyScrollTop : documentScrollTop;
return scrollTop;
}
// 文档的总高度
function getScrollHeight() {
let scrollHeight = 0;
let bodyScrollHeight = 0;
let documentScrollHeight = 0;
if (document.body) {
bodyScrollHeight = document.body.scrollHeight;
}
if (document.documentElement) {
documentScrollHeight = document.documentElement.scrollHeight;
}
scrollHeight =
bodyScrollHeight - documentScrollHeight > 0
? bodyScrollHeight
: documentScrollHeight;
return scrollHeight;
}
// 浏览器视口的高度
function getWindowHeight() {
let windowHeight = 0;
if (document.compatMode === "CSS1Compat") {
windowHeight = document.documentElement.clientHeight;
} else {
windowHeight = document.body.clientHeight;
}
return windowHeight;
}
window.onscroll = function () {
const num = getScrollHeight() - getWindowHeight() - getScrollTop(); // 最小0
const headHeight = document.getElementById("head").offsetHeight; //头部高
const navHeight = document.getElementById("nav").offsetHeight; //导航高
const footHeight = document.getElementById("foot").offsetHeight; //底部高
const sideHeight = document.getElementById("slide").offsetHeight; // fixed定位元素高
const show = getWindowHeight() - headHeight - navHeight - sideHeight; // 网页可视高 - 头高 - 导航高 - fixed元素高
if (num - footHeight + show > 0) { //为什么这么计算自己想,前面对应的值都有解释
document.querySelector("#slide").style = "top:180px";
} else {
const topnum = (function () {
const counter = 180; // fixed元素初始top值
return function () {
return counter + num - footHeight + show;
};
})();
document.querySelector("#slide").style = "top:" + topnum() + "px";
}
};
}