javascript 使用IntersectionObserver时滚动滞后

rmbxnbpk  于 2022-12-21  发布在  Java
关注(0)|答案(1)|浏览(149)

我想确保在滚动到某个特定元素的那一刻,它固定在页面上,向下滚动时一直是这样,直到跨越另一个类的那一刻,它都是隐藏的
我写了这段代码,一切似乎都在工作,它在需要的地方出现和隐藏,但当页面滚动时,这个固定元素疯狂地滞后。
有什么问题吗?

let isFooterVisible = false;
$(document).scroll(function() {
  var y = $(this).scrollTop();
  if (y > $('.btn').offset().top && isFooterVisible === false) {
    $('.btn').addClass("fixed");
  } else {
    $('.btn').removeClass("fixed");
  }
});
function isIntoView(entries, obs){
  entries.forEach(entry => {
     if (entry.target.id === 'end'){
       if (entry.isIntersecting === true){
         isFooterVisible = true;
         $('.btn').removeClass("fixed");
       }
       else{
         isFooterVisible = false;
       }
     } 
  });
}
let options = {
  root: null,
  rootMargin: '0px',
  threshold: 0
};
let observer = new IntersectionObserver(isIntoView, options);
let target = $('#end')[0];
observer.observe(target);
.info {
  margin: 100px auto;
  text-align: center;
}

.btn {
  width: 200px;
  padding: 12px 50px;
  background-color: blue;
  margin: 0 auto;
  text-align: center;
}

.fixed {
  position: fixed;
  z-index: 99;
  bottom: 0;
  left: 50%;
  transform: translate(-50%, -50%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="info">info</div>
<div class="info">info</div>
<div class="info">info</div>
<div class="info">info</div>
<div class="info">info</div>
<div class="info">info</div>
<div class="info">info</div>
<div class="info">info</div>
<div class="btn">button</div>
<div class="info">info</div>
<div class="info">info</div>
<div class="info">info</div>
<div class="info">info</div>
<div class="info">info</div>
<div class="info">info</div>
<div class="info">info</div>
<div class="info">info</div>
<div class="info" id="end">info</div>
<div class="info">info</div>
<div class="info">info</div>
<div class="info">info</div>
<div class="info">info</div>
<div class="info">info</div>
rkue9o1l

rkue9o1l1#

将您的代码更改为

let isFooterVisible = false;
$(document).scroll(function () {
    var y = $(this).scrollTop();
    if ( isFooterVisible === false) {
        $('.btn').removeClass("fixed");
    } else {
        if (!$('.btn').hasClass('fixed')) {
            $('.btn').addClass("fixed");
        }
    }
});
function isIntoView(entries, obs) {
    entries.forEach(entry => {
        if (entry.target.id === 'end') {
            if (entry.isIntersecting === true) {
                isFooterVisible = true;
            }
            else {
                isFooterVisible = false;
            }
        }
    });
}

相关问题