gpt4 book ai didi

javascript - 滚动功能未在我想要的位置触发

转载 作者:行者123 更新时间:2023-12-03 06:47:11 27 4
gpt4 key购买 nike

我有一个窗口滚动功能,我正在尝试拨入。最初,我尝试使用航路点,但无法弄清楚。

我的问题是我的函数触发得太早,并且不在我想要的位置。当屏幕底部到达主容器(全部位于 #home-info 中)时,它会触发。我遇到的问题是,如果有人滚动缓慢,他们就看不到动画。理想情况下,我希望该函数在到达 #info-container(其中包含动画对象的容器)时触发。

我做错了什么不允许这种情况发生,或者有更好的方法来做到这一点吗?

Fiddle. See it here

function boxes() {
window.addEventListener("scroll", function(event) {

var top, green, yellow, red;

top = this.scrollY;

green = document.querySelector("#green"),
yellow = document.querySelector("#yellow"),
red = document.querySelector("#red");

if(top > 100){
green.classList.add("green", "active");
yellow.classList.add("yellow", "active");
red.classList.add("red", "active");
}
}, false);
}
setTimeout(boxes,1200);


<div id="home-info">
<div id="home-info-container">
<div id="home-info-container">
<div id="home-info-container-description">
<div id="home-info-container-title">THE <span class="yellow-color sansbold">LEADING</span> PROVIDER FOR<br> DEMOLITION & WRECKING</div>
<div id="home-info-description">The Eslich Wrecking Company has been recognized as a leader in the demolition field for over 60 years. Over that time span, we have gained both the experience and reputation for doing quality work in an expedient, safe and cost efficient manner. Our track record proves that Eslich Wrecking has the people, equipment and know-how to tackle even the most complex situations and the most demanding jobs. This includes the capability to bond any project when necessary and to carry general liability, auto, and pollution insurance up to 10 million.</div>
</div>
</div>
<section id="info">
<article id="info-container">
<a href="projects">
<div id="green" class="box">
<div class="info-box-title">PROJECT AFTER PROJECT</div>
<div class="info-box-description">Over 60 years of accumulated projects.</div>
</div>
</a>
<a href="about">
<div id="yellow" class="box">
<div class="info-box-title">YEARS OF DEMOLITION HISTORY</div>
<div class="info-box-description">Find out about - The Eslich Wrecking Company.</div>
</div>
</a>
<a href="contact">
<div id="red" class="box">
<div class="info-box-title">GET IN TOUCH WITH US</div>
<div class="info-box-description">Contact us for more information.</div>
</div>
</a>
</article>
</section>
</div>

最佳答案

您不想对滚动条位置进行硬编码。对象可见的位置取决于视口(viewport)的高度,但更重要的是取决于目标元素上方有多少内容。

使用如下内容定义变量目标:

var target = $('#info-container').offset().top;
if(top >= target) {
// start animation
}

另请注意,如果您不查看窗口的高度,则滚动顶部不会告诉您视口(viewport)中的内容。在上面的情况下,使用类似

var top = this.scrollY + $(window).height();

一旦 #info-container 滚动到 View 中,这将为您提供一个评估为 true 的条件。根据您的需要,如果您希望滚动开始一次,您可能希望您的 target 还包含 $('#info-container').height() 整个 #info-container 都在 View 中。

关于javascript - 滚动功能未在我想要的位置触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37683115/

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