当窗口底部经过一个点时,JavaScript会褪色

JavaScript fade when window bottom passes a point

本文关键字:JavaScript 褪色 一个 底部 窗口 经过      更新时间:2023-09-26

我有一个div被另一个div覆盖,当窗口底部大于div的一半时,我试图让盖子逐渐消失(露出下面的div)。当顶部碰到窗口顶部时,我可以让它开始褪色,但从那以后我编辑了它,它再也不起作用了。

以下是一个JSfiddle示例:http://jsfiddle.net/DnJ2z/676/

这是我的JavaScript代码:

$(document).ready(function() {
    var scrollBottom = $(window).scrollTop() + $(window).height();
    var middleofDiv = $("#redCover").offset().top + (document.getElementById('redCover').clientHeight/2);
    $(window).scroll(function() {
        if(scrollBottom > middleofDiv) { //scrolled past the other div?
            $("#redCover").fadeOut(2000); //reached the desired point -- show div
        }
    });
  });

对于这个例子,我希望它能在窗口底部位于绿色div的一半以上时触发渐变。

顺便说一句,我在页面上有三个这样的Div+coveredDiv,都是"背景"answers"封面"。如果我能让这个Javascript工作,有没有办法让它适用于所有类而不是单个元素?

谢谢你的帮助!

您的问题是scrollTop()根据滚动到的位置而不同。您运行的是onload,所以它总是一样的。它需要在您的scroll事件中运行。试试这个:

$(function(){
  var rC = $('#redCover'), middleofDiv = rC.offset().top + (rC.height()/2);
  $(window).scroll(function(){
    if($(window).scrollTop() + $(window).height() > middleofDiv){
      //scrolled past the other div?
      rC.fadeOut(2000); //reached the desired point -- show div
    }
  });
});

Fiddle

如承诺:

$(window).scroll(function(){
  var sT = $(window).scrollTop(), wH = $(window).height();
  $('.color').each(function(){
    var ths = $(this);
    if(sT + wH > ths.offset().top + (ths.height()/2)){
      ths.fadeOut(2000);
    };
  });
});

Fiddle

请注意,您确实在#redCover周围有#greenDiv