使用 jquery 滚动时淡入淡出

Fade in and out when scrolling with jquery

我想在每次滚动一定数量的像素时显示一个 div,并在更多滚动后淡出。我发现了一些逻辑,但是最后有一个冲突,div 再次淡入,正如我所说,每次滚动 > 250 时它都会淡入。 我该如何解决?

$('#1').hide();

$(window).scroll(function() {
  if ($(this).scrollTop() > 250) { //use `this`, not `document`
    $('#1').fadeIn();
  }
  if ($(this).scrollTop() > 1250) { //use `this`, not `document`
    $('#1').fadeOut();
  }
});  

仅当 scrollTop 值小于或等于 1250 时显示元素。

if ($(this).scrollTop() > 250 && $(this).scrollTop() <= 1250){
   $('#1').fadeIn();
} 

虽然可以用stop()停止上一个动画

$(window).scroll(function() {
  if ($(this).scrollTop() > 250) {
    if ($(this).scrollTop() > 1250) 
       $('#1').stop().fadeOut();
    else
       $('#1').stop().fadeIn();
  }
});  

问题是你的逻辑有问题。您需要照顾 scrollTop 不在您当前 if 条件范围内的情况。试试这个:

$(window).scroll(function() {
  if ($(this).scrollTop() > 250 && $(this).scrollTop() < 1250) {
    $('#1').fadeIn();
  } else {
    $('#1').fadeOut();
  }
}); 

Working example

请注意,在上面的示例中,我必须更改 id 以使其不以数字开头,因为 Chrome.

中存在问题