我有一个窗口滚动功能,我正在尝试拨入。最初,我尝试使用航点,但无法弄明白。
我的问题是我的功能太早发射而不是我想要的位置。当屏幕底部到达主容器时,它会触发,#home-info
。我遇到的问题是,如果某人滚动速度慢,他们永远不会看到动画。理想情况下,我希望函数在到达#info-container
时触发,该容器中包含动画对象。
我做错了什么是不允许这种情况发生或有更好的方法来做到这一点?
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>
答案 0 :(得分:1)
您不想硬编码滚动条位置。对象变为可见的位置取决于视口的高度,但更重要的是取决于目标元素上方有多少内容。
使用以下内容定义变量目标:
var target = $('#info-container').offset().top;
if(top >= target) {
// start animation
}
另请注意,滚动 top 不会告诉您视口中的内容,如果您还没有查看窗口的高度。在上述条件中,使用类似
的内容var top = this.scrollY + $(window).height();
一旦#info-container
滚动到视图中,这将为您提供一个评估为true的条件。根据您的需要,您可能希望target
也包含$('#info-container').height()
,如果您希望在整个 #info-container
可见后启动滚动条。