gpt4 book ai didi

javascript - 当我滚动到 div ID 时显示 div

转载 作者:太空宇宙 更新时间:2023-11-04 02:04:32 25 4
gpt4 key购买 nike

所以我认为这是一个非常直截了当的问题,但我在这里找不到我正在寻找的正确答案。如果之前有人问过这个问题,请原谅我。

我有一个部分 section id="front-page-item-4"。在这个 部分 中,我有一个名为 about-us-short 的 div。我想要的是当您滚动经过 front-page-item-4 时让 div about-us-short 淡入。我找到了这段代码,但这只是让 div about-us-short 淡入淡出,而不是当我滚动到 front-page-item-4 时。

我做错了什么?看起来这段代码正在寻找 div front-page-item-4height 但我不知道这个 div 的高度也不知道偏移量.. .

$(window).scroll(function () {
console.log($(window).scrollTop());
var topDivHeight = $("#front-page-item-4").height();
var viewPortSize = $(window).height();

var triggerAt = 150;
var triggerHeight = (topDivHeight - viewPortSize) + triggerAt;

if ($(window).scrollTop() >= triggerHeight) {
$('.about-us-short').css('visibility', 'visible').hide().fadeIn();
$(this).off('scroll');
}
});

提前感谢您的帮助...

最佳答案

一个优雅的解决方案是,如果您动态获取特定 div 的顶部偏移量,在您的情况下为 #front-page-item-4。然后您可以检查 $(window).scroll() 方法是否已达到元素的偏移顶部。如果是,淡入您想要的 div about-us-short

要获取元素的偏移量,您可以使用 jQuery offset()方法。

HTML

<section id="first">
<h1>First</h1>
</section>

<section id="second">
<h1>Second</h1>
<div id="show">Second div reached. Show me</div>
</section>

CSS

#first{
height: 200px;
background: #eee;
}

#second{
height: 800px;
background: rgba(0,0,0,0.3);
}

#show{
display: none;
}

jQuery

var offsetTop = $("#second").offset().top;

$(window).scroll(function(){
var scrollTop = $(window).scrollTop();
if(scrollTop > offsetTop){
$("#show").fadeIn(200);
}
});

var offsetTop = $("#second").offset().top;

$(window).scroll(function() {
var scrollTop = $(window).scrollTop();
if (scrollTop > offsetTop) {
$("#show").fadeIn(200);
}
});
#first {
height: 200px;
background: #eee;
}
#second {
height: 800px;
background: rgba(0, 0, 0, 0.3);
}
#show {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="first">
<h1>First</h1>
</section>

<section id="second">
<h1>Second</h1>
<div id="show">Second div reached. Show me</div>
</section>

关于javascript - 当我滚动到 div ID 时显示 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41057027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com