如何在页面加载时开始执行javascript代码?

loading...


-1

我有一个计数器javascript代码 . 它工作正常,但我希望计数器开始执行onscroll但不知道如何做到这一点 . 对此有何帮助?

<script type="text/javascript">
     $(document).ready(function () {
        var dataval = parseInt($('.progress').attr("data-amount"));
        if (dataval < 100) {
            $('.progress .amount').css("width", 0 + dataval + "%");
        }

        function modifyProgressVal(type) {
            dataval = parseInt($('.progress').attr("data-amount"));
            if (type == 1)
                dataval = Math.min(100, dataval + 10)
            else if (type == -1)
                dataval = Math.max(0, dataval - 10);
            $('.progress .amount').css("width", 100 - dataval + "%");
            $('.progress').attr("data-amount", dataval);
        }
    });
</script>

loading...

3回答

  • 0

    您可以在文档上添加滚动事件侦听器,如下所示:

    document.addEventListener("scroll", () => {
     // execute code on scroll
    });
    

  • 0

    Headers 和问题有点让人困惑,但我想你可能希望在加载和滚动时调用你的函数;详细阐述Alex的答案,这应该有效:

    document.addEventListener("scroll", () => {
        // execute code on scroll
    });
    
    document.dispatchEvent(new Event("scroll"));
    

  • 0

    添加.scroll功能:

    $(document).ready(function () {
    $(document).scroll(function() {
        var dataval = parseInt($('.progress').attr("data-amount"));
        if (dataval < 100) {
            $('.progress .amount').css("width", 0 + dataval + "%");
        }
    
        function modifyProgressVal(type) {
        dataval = parseInt($('.progress').attr("data-amount"));
        if (type == 1) dataval = Math.min(100,dataval + 10)
        else if (type == -1) dataval = Math.max(0,dataval - 10);
        $('.progress .amount').css("width", 100 - dataval + "%");
        $('.progress').attr("data-amount", dataval);
    }
    }
    
评论

暂时没有评论!