首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在滚动条上只做一次动画

如何在滚动条上只做一次动画
EN

Stack Overflow用户
提问于 2017-06-25 17:46:54
回答 3查看 44关注 0票数 0

这是我的代码:Fiddle

代码语言:javascript
运行
复制
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));
        }
    });
}
代码语言:javascript
运行
复制
<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。

EN

Stack Overflow用户

发布于 2017-06-25 18:00:26

使用全局变量。在开始时将其设置为false。在scroll事件中,选中它,如果它仍然是false,则运行countEach()函数,然后将变量更改为true。如下所示:

代码语言:javascript
运行
复制
var stop = false;

countEach();
$(window).on('scroll', function(e) {
  if(!stop){
    countEach();
    stop = true;
  }
})
票数 1
EN
查看全部 3 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44745123

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档