我找到了一个脚本来改变滚动的不透明度并稍微修改它。 div退色很好,但是当我回到顶部时,我似乎无法扭转褪色。
当它到达顶部时,我可以让浏览器“警告”我,但不透明度部分没有触发,似乎无法找出原因。
$(document).ready(function() {
/* Every time the window is scrolled ... */
$(window).scroll(function() {
/* Check the location of each desired element */
$('.hideme').each(function(i) {
var bottom_of_object = $(this).offset().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
/* If the object is completely visible in the window, fade it it */
if (bottom_of_window > bottom_of_object) {
$(this).animate({
'opacity': '1'
}, 500);
}
/*attempt to fade it out*/
var scrollPosition = $("body, html").scrollTop();
if (scrollPosition == 0) {
$(this).animate({
'opacity': '0'
}, 500);
}
});
});
});
#container {
height: 2000px;
}
#container DIV {
margin: 50px;
padding: 50px;
background-color: lightgreen;
}
.hideme {
opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div>Hello</div>
<div class="hideme">Fade In</div>
</div>
该代码有几个问题:
bottom_of_window
移出each
bottom_of_object
或bottom_of_window
任何东西,只需要一点offset
例如+100
为bottom_of_window
fadeOut
,只需使用else
条件。$("body, html").scrollTop();
使用$(window).scrollTop()
animation
时,你最好使用stop()
来防止fadeIn
和fadeOut
效果之间的冲突。如有变化,请点击此处:
$(window).scroll(function() {
var bottom_of_window = $(window).scrollTop() + 100;
$('.hideme').each(function(i) {
var bottom_of_object = $(this).offset().top;
if (bottom_of_window > bottom_of_object) {
$(this).stop().animate({
'opacity': '1'
}, 500);
} else {
$(this).stop().animate({
'opacity': '0'
}, 500);
}
});
});
#container {
height: 2000px;
}
#container div {
margin: 50px;
padding: 50px;
background-color: lightgreen;
}
.hideme {
opacity: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div>Hello</div>
<div class="hideme">Fade In</div>
<div class="hideme">Fade In 2</div>
<div class="hideme">Fade In 3</div>
</div>
你可以使用fadeIn(500)
或fadeOut(500)
而不是$(this).animate({'opacity':'1'},500);