繁体   English   中英

如何只滚动1次制作动画

[英]how to make an animation only 1 time on scroll

这是我的代码: 小提琴

 countEach() $(window).on('scroll', function(e) { countEach() }) function countEach() { $('.count').each(function() { if (showOnScreen(this) && $(this).attr('show') != 'false') { console.log($(this).text()) console.log($(this).attr('show')) $(this).attr('show', 'false') numberAnimate(this) } else if (!showOnScreen(this)) { $(this).attr('show', 'true') } }) } function showOnScreen(target) { if ($(window).scrollTop() + $(window).height() >= $(target).offset().top) return true; else return false; } function numberAnimate(target) { var $this = $(target); jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, { duration: 1000, easing: 'swing', step: function() { $this.text(this.Counter.toFixed(1)); } }); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="count">5.6</span> <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/> <p>Scroll up and then scroll down again</p> <span class="count">5.6</span> 

问题是,如果我向上滚动并再次向下滚动,则越来越多的动画将再次运行。 我需要更改以阻止它的事情是什么? 我尝试了很多事情,但是我不擅长Javascript。

使用全局变量。 一开始将其设置为false 在滚动事件中,对其进行检查,如果仍然为false ,请运行countEach()函数,然后将该变量更改为true 像这样:

var stop = false;

countEach();
$(window).on('scroll', function(e) {
  if(!stop){
    countEach();
    stop = true;
  }
})

您需要将全局stopNow = 2声明为stopNow = 2以便动画只能运行两次,并在动画运行时将其递减。

var stopNow = 2;

如下更新countEach函数

function countEach() {
    $('.count').each(function() {
        //also check stopNow != 0
        if (showOnScreen(this) && $(this).attr('show') != 'false' && stopNow != 0) {
            console.log($(this).text())
            console.log($(this).attr('show'))
            $(this).attr('show', 'false')
            numberAnimate(this)
            stopNow = stopNow - 1;  //decrement stopNow
        } else if (!showOnScreen(this)) {
            $(this).attr('show', 'true')
        }
    })
}

这是您更新的工作提琴-https: //jsfiddle.net/6w8ubh5y/7/

从以下位置更改事件绑定代码:

$(window).on('scroll', function(e) {
    countEach()
})

$(window).on('scroll', countEach);

并像这样更改countEach函数...

function countEach() {
    $('.count').each(function() {
        ...
    });

    $(window).off('scroll', countEach); // add this line
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM