我想确保在滚动到某个特定元素的那一刻,它固定在页面上,向下滚动时一直是这样,直到跨越另一个类的那一刻,它都是隐藏的
我写了这段代码,一切似乎都在工作,它在需要的地方出现和隐藏,但当页面滚动时,这个固定元素疯狂地滞后。
有什么问题吗?
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>
1条答案
按热度按时间rkue9o1l1#
将您的代码更改为