嗨我需要animate元素取决于滚动。我的观点是设置在顶部位置1200px上的元素,但是在1000px上开始制作动画并在通过1800px时完成它然而它在1400px开始动画并完成谁知道在哪里
HTML
<div class="container">
<section id="first-section"></section>
<section id="second-section"></section>
</div>
CSS
#second-section {
position: relative;
top: 1200px;
left: 0;
height: 200px;
border: 2px solid blue;
width: 100%;
background-color: red;
opacity: 1;
}
JAVASCRIPT
$(window).scroll(function() {
var top = $(this).scrollTop();
if (top > 1000 && top < 1800) {
$("#second-section").stop().animate({
opacity: "1"
}, 'slow');
} else {
$("#second-section").stop().animate({
opacity: "0"
}, 'slow');
}
});
答案 0 :(得分:0)
你的病情不对。为此,您需要获取元素的height
和position
。
参见我的例子
$(window).scroll(function() {
var winHeight = $(this).height();
var scrollTop = $(this).scrollTop();
var elemHeight = $("#first-section").height();
var elementTop = $("#first-section").position().top;
if (elementTop < scrollTop + winHeight && scrollTop < elementTop + elemHeight)
var opacity = 1;
else
var opacity = 0;
$("#first-section").stop().animate({
opacity: opacity
}, "slow");
});
.container {
height: 2000px;
}
#first-section {
position: relative;
top: 1200px;
left: 0;
height: 200px;
border: 2px solid blue;
width: 100%;
background-color: red;
opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<section id="first-section"></section>
</div>