如何在滚动时只制作一次动画

时间:2017-06-25 09:46:54

标签: javascript html css

这是我的代码:Fiddle



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>
&#13;
&#13;
&#13;

问题是,如果我向上滚动并再次向下滚动,则增加的动画数量将再次运行。为了阻止它,我需要改变什么?我尝试了很多东西,但我不擅长Javascript。

3 个答案:

答案 0 :(得分:1)

使用全局变量。在开头将其设置为false。在滚动事件中,选中它,如果它仍然是false,请运行countEach()函数,然后将变量更改为true。像这样:

var stop = false;

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

答案 1 :(得分:1)

您需要将全局变量声明为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/

答案 2 :(得分:0)

更改事件绑定代码:

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

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

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

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

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