$(window).scroll结合了类似的功能

时间:2017-01-08 18:39:11

标签: javascript jquery

我有几个数字计数器,并希望它们在用户向下滚动时开始制作动画。现在,我通过为每个人编写一个函数来实现这一点,但我确信这是一种低效的方法。

我在这里有一个有效的例子:     https://codepen.io/adogandesign/pen/PWqVov

HTML:

<div id="states" class="animated">
    <div class="anim_num">
        <svg>
            <pattern>...</pattern>
            <text id="count_num1"></text>
        </svg>
    </div>
</div>
<div id="concerts" class="animated">
    <div class="anim_num">
        <svg>
            <pattern>...</pattern>
            <text id="count_num2"></text>
        </svg>
    </div>
</div>

Javascript:

$(window).scroll(startCounter1);
    function startCounter1() {
        if ($(window).scrollTop() > $("#states").offset().top - $(window).height() + 0) {
            $(window).off("scroll", startCounter1);
        $("#count_num1").each(function () {
                var $this = $(this);
                jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
                    duration: 4000,
                    easing: 'swing',
                    step: function (now) {
                        $this.text(now.toFixed(0));
                    }
                });
            });
        }
    }
$(window).scroll(startCounter2);
    function startCounter2() {
        if ($(window).scrollTop() > $("#concerts").offset().top - $(window).height() + 0) {
            $(window).off("scroll", startCounter2);
        $("#count_num2").each(function () {
                var $this = $(this);
                jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
                    duration: 4000,
                    easing: 'swing',
                    step: function (now) {
                        $this.text(now.toFixed(0));
                }
                });
            });
        }
    }

我的问题是我如何将这个javascript代码组合成一个函数?

3 个答案:

答案 0 :(得分:1)

您可以用于重构此类的一般算法是:

  1. 识别不同的部分。
  2. 用变量名替换这些部分。
  3. 创建一个函数包装器,用函数参数替换这些变量。
  4. 使用对该功能的调用替换代码。
  5. 所以在这种情况下,第一个方差是"#states" vs "#concerts";让我们称之为section。第二个是#count_num1 vs #count_num2,我们可以将其称为counter。现在我们可以这样做:

    function createScrollCounter(section, counter) {
      $(window).scroll(scrollCounter);
    
      function scrollCounter() {
        if ($(window).scrollTop() > $(section).offset().top - $(window).height() + 0) {
          $(window).off("scroll", scrollCounter);
          $(counter).each(function () {
            var $this = $(this);
            jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
              duration: 4000,
              easing: 'swing',
              step: function (now) {
                $this.text(now.toFixed(0));
              }
            });
          });
        }
      }
    }
    
    createScrollCounter('#states', '#count_num1');
    createScrollCounter('#concerts', '#count_num2');
    

答案 1 :(得分:0)

使用each循环遍历公共类,而不是关注单个ID并处理该循环中的每个实例

类似的东西:

   $('.animated').each(function() { // #states & #concerts
      // current instance of the animated class
      var $this = $(this),
        // find associated text element, 
        // will be  #count_num1 or #count_num2 depending on $this instance  
        $textEl = $this.find('text'); 
      // check instance offset
      if ($(window).scrollTop() > $this.offset().top - $(window).height() + 0) {
        jQuery({
          Counter: 0
        }).animate({
          Counter: $textEl.text()
        }, {
          duration: 4000,
          easing: 'swing',
          step: function(now) {
            $textEl.text(now.toFixed(0));
          }
        });
      }

    });

请注意,您可能想要检查动画是否已经发生,然后再次为滚动的每个像素移动重新初始化动画

答案 2 :(得分:0)

简单地给每个文本标签赋予类似“动画”的相同类别,并从那里删除id(count_num1,count_num2)并在 $(“#count_num1”)中使用$(“。animation”)我有在您的codepen链接中检查此方法,它完美地工作。

$(window).scroll(startCounter1);
  function startCounter1() {
    if ($(window).scrollTop() > $("#states").offset().top - $(window).height() + 0) {
      $(window).off("scroll", startCounter1);
      $(".animation").each(function () {
	  var $this = $(this);
	  jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, 
      {
	    duration: 4000,
		easing: 'swing',
		step: function (now) {
		$this.text(now.toFixed(0));
      }
    });
  });
  }
}
body{
  width: 100%;
  overflow-x: hidden;
  font-family: Open Sans, sans-serif;
}

.scrolldown {
  width: 100%;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 50px;
}

.animated_percentage {
  max-width: 100%;
  margin: 0 auto;
  position: relative;
}

.anim_num {
  display: block;
  position: relative;
  max-height: 100vh;
  padding: 5% 0;
  font-size: 350px;
  font-weight: 900;
}
#states .anim_num {
  padding-left: 20%;
}
#concerts .anim_num {
  padding-right: 30%;
}
#fans .anim_num {
  padding-left: 15%;
}

svg {
  max-width: 100%;
  max-height: 100%;
}

#count_num1{
  fill: url(#img1);
}
#count_num2{
  fill: url(#img2);
}
#count_num3{
  fill: url(#img3);
}

.exp {
  position: absolute;
  top: 50%;
  font-size: 48px;
  font-weight: 700;
  color: #aabbae;
}
#states .exp {
  left: 10%;
}
#concerts .exp {
  right: 20%;
}
#fans .exp {
  left: 5%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="scrolldown">
  Scroll down to see the animation
</div>  
<div id="states" class="animated_percentage">
<div class="anim_num">
<svg viewBox="0 0 960 540">
    <pattern id="img1" patternUnits="userSpaceOnUse" width="100%" height="100%" x="-10%" y="-25%">
    <image xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://adogandesign.com/wp-content/uploads/2017/01/AdobeStock_69678727.jpg" width="960" height="540"></image>
    </pattern>
  <text text-anchor="middle" x="50%" y="50%" class="animation" id="count_num1">46</text>
   </svg>
</div><!--#anim_num-->
  <div class="exp">
     States travelled
  </div>  
</div>

<div id="concerts" class="animated_percentage">
<div class="anim_num">
<svg viewBox="0 0 960 540">
    <pattern id="img2" patternUnits="userSpaceOnUse" width="100%" height="100%" x="0" y="-20%">
    <image xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://adogandesign.com/wp-content/uploads/2017/01/AdobeStock_63664078.jpg" width="960" height="540"></image>
    </pattern>
  <text text-anchor="middle" x="50%" y="50%" class="animation" id="count_num2">97</text>
   </svg>
</div><!--#anim_num-->
  <div class="exp">
     Concerts Given
  </div>  
</div>

<div id="fans" class="animated_percentage">
<div class="anim_num">
<svg viewBox="0 0 960 540">
    <pattern id="img3" patternUnits="userSpaceOnUse" width="100%" height="100%" x="0" y="-22%">
    <image xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="http://adogandesign.com/wp-content/uploads/2017/01/AdobeStock_93833225.jpg" width="960" height="540"></image>
    </pattern>
  <text text-anchor="middle" x="50%" y="50%" class="animation" id="count_num3">436</text>
   </svg>
</div><!--#anim_num-->
  <div class="exp">
     Fans Gone Wild
  </div>  
</div>