gpt4 book ai didi

javascript - 当滚动条到达特定位置时动画 div

转载 作者:行者123 更新时间:2023-11-28 01:31:13 24 4
gpt4 key购买 nike

目前,我的网站在单个滚动布局中包含三个部分。有两个部分的标题:关于和联系(这些是 div 框),当您滚动到页面底部时,它们会动画。我想要实现的是让动画在用户向下滚动并点击每个(div 框)部分的底部而不是网站底部时发生。

我认为我需要实现 .offset() 函数但不确定这是否正确?

如有任何帮助,我们将不胜感激。

CSS

.header {
display: none;
position: relative;
left: 0px;
right: 0px;
top: 500px;
height: 80px;
width: 100%;
background:red;
color: #fff;
text-align: center;
}

JS

var header = $('.header'),
extra = 10; // In case you want to trigger it a bit sooner than exactly at the bottom.

header.css({ opacity: '0', display: 'block' });

$(window).scroll(function() {

var scrolledLength = ( $(window).height() +extra) + $(window).scrollTop(),
documentHeight = $(document).height();

console.log( 'Scroll length: ' + scrolledLength + ' Document height: ' + documentHeight )

if( scrolledLength >= documentHeight ) {

header
.addClass('top')
.stop().animate({ top: '20', opacity: '1' }, 800);
}
else if ( scrolledLength <= documentHeight && header.hasClass('top') ) {
header
.removeClass('top')
.stop().animate({ top: '500', opacity: '0' }, 800);
}
});

fiddle - http://jsfiddle.net/SFPpf/480/

最佳答案

在这种情况下,position() 看起来会更好。 position 方法是相对于文档的,而 offset 是相对于父元素的。它返回一个具有属性“top”和“left”的对象。它一次只能返回一个元素的位置,因此对于第一个 div,您需要使用 first() 和 eq() 来获取特定元素。

.fillWindow 的底部将是其垂直位置 + 高度。

var $fillWindow = $(".fillWindow").first(), // or eq() for others
position = $fillWindow.position(),
height = $fillWindow.height();
//bottom = position.top + height;

scrollTop() 现在可用于检查用户何时滚动经过 .fillWindow。

if ( $(window).scrollTop() >= position.top ) {
// do the animation here
} else {
// do something else
}

编辑:我刚刚发现了我的错误。它应该是 $(window).scrollTop()。您还应该只测试 scrollTop 是否位于 .fillWindow 的顶部。

关于javascript - 当滚动条到达特定位置时动画 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30205442/

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