Previous Article Next Article Javascript – 滾動螢幕後再讓數字跑 – window scroll and animate
Posted in Script

Javascript – 滾動螢幕後再讓數字跑 – window scroll and animate

Javascript – 滾動螢幕後再讓數字跑 – window scroll and animate Posted on 2018 年 09 月 13 日Leave a comment
<style>
    #hight {
        width: 100%;
        height: 1280px;
        position: relative;
    }
</style>

<div id="hight"></div>

<div id="counter">
    <span class="counter-value" data-count="64">64</span><span class="number_turns">%</span>
    <span class="counter-value" data-count="70">70</span><span class="number_turns">%</span>
    <span class="counter-value" data-count="100">100</span><span class="number_turns">%</span>
</div>
<br>
<br>
<br>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>
    var a = 0;
    $(window).scroll(function() {

        console.log( '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>' );
        console.log( '#counter.width()=' + $('#counter').width() );
        console.log( '#counter.height()=' + $('#counter').height() );
        console.log( '#counter.innerWidth()=' + $('#counter').innerWidth() );
        console.log( '#counter.innerHeight()=' + $('#counter').innerHeight() );
        console.log( '#counter.outerWidth()=' + $('#counter').outerWidth() );
        console.log( '#counter.outerHeight()=' + $('#counter').outerHeight() );
        console.log( '#counter.offset().top=' + $('#counter').offset().top ); // =$(window).scrollTop()
        console.log( 'window.innerHeight=' + window.innerHeight );
        console.log( 'window.scrollTop()                      =' + $(window).scrollTop() );
        var oTop = $('#counter').offset().top - window.innerHeight;
        console.log( '#counter.offset().top-window.scrollTop()=' + oTop );
        console.log( 'see the counter if window.scrollTop() > (#counter.offset().top - window.innerHeight)');


        var oTop = $('#counter').offset().top - window.innerHeight;
        if (a == 0 && $(window).scrollTop() > oTop) {
            $('.counter-value').each(function() {
                var $this = $(this),
                countTo = $this.attr('data-count');
                $({
                countNum: 0
                }).animate({
                    countNum: countTo
                },
                {
                    duration: 2000,
                    easing: 'swing',
                    step: function() {
                        $this.text(Math.floor(this.countNum));
                    },
                        complete: function() {
                        $this.text(this.countNum);
                    }
                });
            });
            a = 1;
        }
    });
</script>

參考 https://codepen.io/dmcreis/pen/VLLYPo

發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *