检测 ScrollTop() 的选项

问题描述 投票:0回答:1

我正在使用ajax加载选项

我需要在滚动选项时检测scrollTop以调用ajax加载更多数据

我搜索了很多关于scrollTop()的选项,但我发现这些选项不支持检测scrollTop();

请问如何解决

她是我的代码:

<html>
<head>
    <title>Webslesson Tutorial | Auto Load More Data on Page Scroll with Jquery & PHP</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="container">
        <select id="load_data"></select>
    </div>
</body>
</html>
<script>
    $(document).ready(function() {
        var limit = 50;
        var start = 0;
        var action = 'inactive';
        function load_country_data(limit, start) {
            $.ajax({
                url: "fetch.php",
                method: "POST",
                data: {
                    limit: limit,
                    start: start
                },
                cache: false,
                success: function(data) {
                    $('#load_data').append(data);
                    if (data == '') {
                        $('#load_data_message').html("<button type='button' class='btn btn-info'>No Data Found</button>");
                        action = 'active';
                    } else {
                        $('#load_data_message').html("<button type='button' class='btn btn-warning'>Please Wait....</button>");
                        action = "inactive";
                    }
                }
            });
        }
        if (action == 'inactive') {
            action = 'active';
            load_country_data(limit, start);
        }
        $(window).scroll(function() {

            console.log($('#load_data').scrollTop());
            console.log($('#load_data').height());

            if ($(window).scrollTop() + $('#load_data').height() > $("#load_data").height() && action == 'inactive') {
                action = 'active';
                start = start + limit;
                setTimeout(function() {
                    load_country_data(limit, start);
                }, 1000);
            }
        });
    });
</script>

这是 fetch.php 的代码:

<?php
if (isset($_POST["limit"], $_POST["start"])) {
    for ($i = $_POST["start"]; $i < $_POST["start"] + $_POST["limit"]; $i++) {
        echo '<option>item ' . $i . '</option>';
    }
}
javascript html-select
1个回答
0
投票

这对我来说很有效......

  window.onscroll=function(){

   let Y=this.scrollY;  // returns the current vertical position

   let X=this.scrollX;  // returns the current horiz position

   if(Y===0){

    // do something

   }

  };

或者,您可能想要调查类似的事件......

  window.visualViewport.onscroll=function(e){

  }; 

...虽然我从来没有用过这个。

© www.soinside.com 2019 - 2024. All rights reserved.