每个语句的for循环是否等效?

时间:2019-10-09 10:31:31

标签: javascript jquery pycharm

我正在为此功能寻找替代方案。可以在其位置创建for循环,仍然具有相同的效果吗?

  $(function() {
    $(window).scroll(function() {


      $('.fadeInBlock').each(function() {

        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 + 200;

        if (bottom_of_window > bottom_of_object) {

          $(this).animate({
            'opacity': '1'
          }, 1000);

        }
      });

    });
  });

原因是IDE识别每个功能存在问题。预先谢谢你。

编辑: 这很奇怪,因为下一批代码可以在EXACT SAME文件中运行

$(function () {
    var text = $(".text");
    $(window).scroll(function () {
        var scroll = $(window).scrollTop();

        if (scroll >= 200) {
            text.removeClass("hidden");
        } else {
            text.addClass("hidden");
        }
        if (scroll + 250 > $('.homeIm2').offset().top) { // when the div with homeIm2 class scrolls into view
            text.hide();
        }
        if (scroll + 250 < $('.homeIm2').offset().top) { // when the div with homeIm2 class scrolls into view
            text.show();
        }


    });
});

1 个答案:

答案 0 :(得分:4)

这可能是您使用for

所要求的解决方案
$(function () {
  $(window).scroll(function () {
    AllClasses = $('.fadeInBlock')
    for(var i=0; i<AllClasses.length; i++){

      var bottom_of_object = $(AllClasses[i]).position().top + $(AllClasses[i]).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 + 200;

      if (bottom_of_window > bottom_of_object) {

        $(AllClasses[i]).animate({
          'opacity': '1'
        }, 1000);

      }
    }
  });
});