页面滚动时,监听滚动定位(记一次前端知识点!)

举例说明先:

在这里插入图片描述
在这里插入图片描述

需求是: 需要把左边红色框里面的目录 盒子 根据右侧滚动条的滚动,随着一起移动;但是到了底部,不能覆盖底部的东西。

专业名词——吸顶

思路:需要监听 滚动时的高度,页面的高度,和要滚动的高度,和对顶部,对底部的高度
上代码:

<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>

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

付煜晨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值