举例说明先:
需求是: 需要把左边红色框里面的目录 盒子 根据右侧滚动条的滚动,随着一起移动;但是到了底部,不能覆盖底部的东西。
专业名词——吸顶
思路:需要监听 滚动时的高度,页面的高度,和要滚动的高度,和对顶部,对底部的高度
上代码:
<div class="tag-area nav-bar" id="scrollElement">
内容为自己的代码...就不展示了
</div>
<style>
.ld-micro-class .nav-bar{
height: auto;
-webkit-box-shadow: none;
line-height: inherit;
box-shadow: none;
}
</style>
/* nav-bar 这个class是你要监听的 要滚动的 div的class*/
/* ld-micro-class 这个class是 nav-bar 这个calss上面的 div*/
<script>
$(document).ready(function() {
// console.log('这个在这里啊')
// if 判断是否是 移动端,如果没有 可删掉if的代码,只保留 else
if(navigator.userAgent.match(/mobile/i)){
var $jobmap_height = $('.showtop').outerHeight()
var $nav_height = $('.job-tab').outerHeight()
var $height = $jobmap_height + $nav_height + $nav_height;
}else{
var $jobmap_height = $('.jobmap-header-section').outerHeight()
var $nav_height = $('.tab-list').outerHeight()
var $height = $jobmap_height + $nav_height + $nav_height;
}
console.log($jobmap_height,$nav_height)
// 滚动监听
$(window).scroll(function(e) {
if ($(window).scrollTop() > $height) {
// console.log(222)
$('.nav-bar')
.addClass('active')
.css({ position: 'fixed', 'z-index': '889','width':'245px','-webkit-box-shadow' : 'none','box-shadow': 'none' })
// 移动端 如果没有可删掉
if (navigator.userAgent.match(/mobile/i)) {
$('.tag-area')
.addClass('active')
.css({ position: 'fixed', 'z-index': '889','top':'0%'})
}
} else {
// console.log(333)
$('.nav-bar')
.removeClass('active')
.css({ position: 'relative', 'z-index': '0','width':'100%' })
// 移动端
if (navigator.userAgent.match(/mobile/i)) {
$('.tag-area')
.removeClass('active')
.css({ position: 'relative', 'z-index': '0'})
}
}
})
// 距离底部的位置
window.addEventListener('scroll', function() {
// 底部的高度
var $height = $('.es-footer-link').outerHeight();
// 获取要操作的 <div> 元素
const divElement = document.getElementById('scrollElement');
const pageHeight = document.documentElement.scrollHeight; // 页面总高度
const windowHeight = window.innerHeight; // 浏览器窗口高度
const scrollPosition = window.pageYOffset; // 当前滚动的位置
// 计算距离底部的位置
const distanceToBottom = pageHeight - (scrollPosition + windowHeight) - $height;
// 说明到了底部要求的高度
if (distanceToBottom <= 0) {
// 到达指定高度后停止移动
divElement.style.position = 'sticky';
}
});
})
</script>