如何在滚动时触发此动画?

时间:2014-08-30 20:20:14

标签: javascript jquery animation

我有这个工作的JS小提琴:http://jsfiddle.net/4v2wK/

// Animate the element's value from x to y:
$({someValue: 40000}).animate({someValue: 45000}, {
    duration: 3000,
     easing:'swing', // can be anything
     step: function() { // called on every step
         // Update the element's text with rounded-up value:
         $('#el').text(commaSeparateNumber(Math.round(this.someValue)));
     }
});

function commaSeparateNumber(val){
    while (/(\d+)(\d{3})/.test(val.toString())){
        val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
    }
    return val;
}

现在我想修改它,以便仅在用户滚动div时触发它,不一定是在它上面悬停,但div在他或她的屏幕中可见。假设这个div位于长页面的底部,当用户到达那里时,动画结束,他们错过了整个节目。

1 个答案:

答案 0 :(得分:0)

这个代码会在你的div顶部250px后触发动画。

isScrolledIntoView();
$(window).scroll(function() {
    isScrolledIntoView(); 
});
function isScrolledIntoView(){
    $('.class').each(function(){   // add the class of the divs you want trigger on scroll over
        var $this = $(this).attr("id");  
        var docViewTop = $(window).scrollTop();
        var docViewBottom = docViewTop + $(window).height();

        var elemTop = $(this).offset().top;
        var elemBottom = elemTop + $(this).height();

        if  ((elemTop >= docViewTop) && (((docViewBottom-250) >= elemTop))){
            // trigger your animation here
            // with $this as a selector
        }
    })