计数器启动javascript中的特定div滚动

时间:2016-03-29 09:32:41

标签: javascript

如何在滚动事件上启动计数器。

var count = 0;
var counter = setInterval(timer, 40);
    function timer(){
        count += 1;
        if(count == 98){
            clearInterval(counter);
        }
        document.getElementById('num').innerHTML = count;
    }

html代码

<h3><span id="num">98</span>+</h3>

1 个答案:

答案 0 :(得分:0)

这是你想要做的一个例子..

<!DOCTYPE>
<html>
    <head>
        <title></title>
        <style>
            #myScroller {
                margin: 10px;
                padding: 10px;
                width: 100px;
                height: 100px;
                background-color: beige;
                display: block;
                overflow-y:auto; 

            }

            #demo {
                margin: 10px;
                padding: 10px;
                width: 100px;
                height: 100px;
                background-color: bisque;
            }
        </style>
    </head>
    <body>

        <div id="myScroller" class="test">
            <br>Test
            <br>Test
            <br>Test
            <br>Test
            <br>Test
            <br>Test
            <br>Test
            <br>Test
            <br>Test
            <br>Test
        </div>

        <div id="demo"></div>

        <script type="text/javascript">
            var myScroller  = document.getElementById("myScroller"),
                demo = document.getElementById("demo");
                myScroller.addEventListener("scroll", function(){

                    var count = 0;
                    var counter = setInterval(timer, 40);
                    function timer() {
                        count += 1;
                        if(count == 98){
                            clearInterval(counter);
                        }
                        demo.innerHTML = count;
                    }
                });

        </script>
    </body>
</html>

这适用于ie> = 9,firefox,opera,chrome