我正在尝试让一个div在滚动时淡出。如果你看envato.com,当你向下滚动时,关于信息淡入,然后当你向上滚动时淡出。现在我正在使用下面的js来实现淡入淡出效果,但是我不确定如何让div淡出。
$(function() {
$(window).scroll( function(){
$('.fadeInBlock').each( function(i){
var bottom_of_object = $(this).position().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
/* Adjust the "200" to either have a delay or that the content starts fading a bit before you reach it */
bottom_of_window = bottom_of_window + 350;
if ( bottom_of_window > bottom_of_object ) {
$(this).animate({'opacity':'1'},500);
}
});
});
}); 发布于 2016-10-15 11:17:12
我只需要在你的代码中添加一个else语句,它会将不透明度改回0,这样每次if语句为false时,也就是说,用户在div出现后向上滚动,它将再次消失,然后重新出现。如下所示:
$(function() {
$(window).scroll( function(){
$('.fadeInBlock').each( function(i){
var bottom_of_object = $(this).position().top + $(this).outerHeight();
var bottom_of_window = $(window).scrollTop() + $(window).height();
/* Adjust the "200" to either have a delay or that the content starts fading a bit before you reach it */
bottom_of_window = bottom_of_window + 350;
if( bottom_of_window > bottom_of_object ){
$(this).animate({'opacity':'1'},500);
}
else{
$(this).animate({'opacity':'0'},500);
}
});
});
}); 发布于 2016-10-15 11:22:43
$(window).on("load",function() {
$(window).scroll(function() {
$(".fade").each(function() {
/* Check the location of each desired element */
var objectBottom = $(this).offset().top + $(this).outerHeight();
var windowBottom = $(window).scrollTop() + $(window).innerHeight();
/* If the element is completely within bounds of the window, fade it in */
if (objectBottom < windowBottom) { //object comes into view (scrolling down)
if ($(this).css("opacity")==0) {$(this).fadeTo(500,1);}
} else { //object goes out of view (scrolling up)
if ($(this).css("opacity")==1) {$(this).fadeTo(500,0);}
}
});
}); $(window).scroll(); //invoke scroll-handler on page-load
});.fade {
margin: 50px;
padding: 50px;
background-color: lightgreen;
opacity: 1;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div>
<div class="fade">Fade In 01</div>
<div class="fade">Fade In 02</div>
<div class="fade">Fade In 03</div>
<div class="fade">Fade In 04</div>
<div class="fade">Fade In 05</div>
<div class="fade">Fade In 06</div>
<div class="fade">Fade In 07</div>
<div class="fade">Fade In 08</div>
<div class="fade">Fade In 09</div>
<div class="fade">Fade In 10</div>
</div>Fade In on Scroll Down, Fade Out on Scroll Up - based on element position in window
https://stackoverflow.com/questions/40054515
复制相似问题