【问题标题】:How to capture scroll event?如何捕获滚动事件?
【发布时间】:2012-11-21 11:51:27
【问题描述】:

我想实现无限滚动。下面是我的布局的简短形式。由于我有一些相对定位的元素,因此不会触发 javascript 滚动事件。

如何解决这个问题,以便触发滚动事件并实现无限滚动?

我的主要布局是:

<div id="container">
    <div class="wrapper">
        <div id="header">
        ...
        </div> <%-- header --%>

        <div id="main">
        ...
        </div>

    </div> <%-- wrapper --%>
</div> <%-- container --%>
<div id="footer">
</div>

我的 CSS 是:

#container {
    position: absolute;
    z-index: 1;
    top: 0;
    bottom: 35px;
    left: 0;
    right: 0;
    overflow-y: auto;      
    overflow-x: hidden;      
}

.wrapper {
    margin: 0 auto;
    width: 960px;
    position: relative;
}   

#header {
    position: relative;
}

#main {
}

#footer {
    z-index: 2;
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 35px;
} 

为了实现无限滚动,我需要进行哪些更改才能在布局中接收浏览器滚动事件?

【问题讨论】:

标签: infinite-scroll


【解决方案1】:

正确的实现方式是:

 <div id="container" onScroll="handleOnScroll();">

<script>
function handleOnScroll() {
        alert("scroll");
    };
</script>

【讨论】:

  • -1 表示没有利用 jQuery 的强大功能来避免使用内联 JavaScript。我也看不出这与“无限”滚动有什么关系。
  • 是的,没有内联 JavaScript 的任何有效答案都会更好。
  • 为什么这比我的解决方案更好?
  • 再一次,仅仅是因为没有“内联”JavaScript。如果您不想使用它,为什么要用jQuery 标记您的问题? Read the accepted answer on this question including the linked article
  • 虽然这可能不是一个好的解决方案,但它是这个问题的完美答案。这个问题与代码质量无关,也与 jQuery 无关。这只是一个基本的“你是如何做 X 的?”题。很多人不使用jQuery,甚至编译成其他语言的JS,所以这个答案仍然告诉他们他们需要知道什么。
【解决方案2】:

编辑:由于您最初使用 标记您的问题...


使用 jQuery 捕获scroll 事件...

HTML:

<div id="container">
    CONTENT
</div> 

jQuery:

$(document).ready(function() {

    $('#container').scroll(function() {
        alert('scroll');
        // presumably your infinite scrolling code here
    });

});

见:http://api.jquery.com/scroll/

【讨论】:

    【解决方案3】:

    这是我在代码中使用的...

     <div id="DataDiv" style="overflow: auto; width: 280px; height:400px; margin-top: 10px;"
                        onscroll="Onscrollfnction();">
          my content here 
     </div>
    

    功能如下

    function Onscrollfnction() {
                var div = document.getElementById('DataDiv');
                div.scrollLeft;
                return false;
            };
    

    内容超过 400 像素后,将开始滚动并无限滚动。 享受

    【讨论】:

    • 但是我怎么能保证页脚总是在不同屏幕尺寸的底部呢?我应该在哪个位置输入您的代码?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 2013-09-28
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多