javascript - 如何在滚动上只制作 1 次动画

标签 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>

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

最佳答案

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

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

关于javascript - 如何在滚动上只制作 1 次动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44745123/

相关文章:

php - 在 Javascript If else 语句中显示 HTML

javascript - 如何在javascript中检测鼠标左键是否被按下

javascript - Cheerio 错误处理程序 Node js

javascript - Float32Array 在与 WebGL (Chrome) 交互时不更新 ArrayBuffer 以反射(reflect)分配的值

html - CSS 表达式

html - 居中动态div

html - 从另一种风格继承另一种风格

javascript - 如何在nodejs中将一个api请求转换为另一个api请求

javascript - 奇怪的 html 渲染异常。

javascript - 可拖动元素问题