我正在努力使一个元素在向下滚动某个像素后首先出现,然后在相同数量的像素向同一方向滚动后使它消失。它也应该消失,如果回到上面的触发点,使它出现,它也应该始终在页面的中心。
现在我唯一的问题是,当我继续向下滚动时,该元素并没有消失,但当滚动回页面顶部时,它确实消失了。
这是我正在使用的代码。有没有什么快速的方法可以让元素再次消失?
var offsetTop = $("#second").offset().top;
var isVisible = false;
var scrollThreshold = 100; // Adjust this value as needed
var scrollDistance = 0;
// Get a reference to the element to show/hide
var $showElement = $("#show");
// Calculate the initial top position to center the element
var windowHeight = $(window).height();
var elementHeight = $showElement.height();
var topPosition = (windowHeight - elementHeight) / 2;
// Set the initial CSS for the centered fixed element
$showElement.css({
position: "fixed",
top: topPosition + "px",
left: "50%",
transform: "translateX(-50%)",
display: "none" // Start hidden
});
$(window).scroll(function() {
var scrollTop = $(window).scrollTop();
if (scrollTop > offsetTop + scrollThreshold && !isVisible) {
// If scrolled 100 pixels or more below the offset point and not visible, make it visible
$showElement.fadeIn(200);
isVisible = true;
scrollDistance = scrollTop; // Record the scroll distance at which it became visible
} else if (isVisible && (scrollTop <= scrollDistance - 200 || scrollTop <= offsetTop - scrollThreshold)) {
// If scrolled 200 pixels or more above the point it became visible, or scrolled back above the initial threshold and currently visible, make it invisible
$showElement.fadeOut(200);
isVisible = false;
}
});
#first{
height: 200px;
background: #eee;
}
#second{
height: 2800px;
background: rgba(0,0,0,0.3);
}
#show{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="first">
<h1>First</h1>
</section>
<section id="second">
<h1>Second</h1>
<div id="show"><pre>Hey!</pre></div>
</section>
1条答案
按热度按时间lxkprmvk1#