lishengzxc / bblog

My Blog
https://github.com/lishengzxc/bblog/issues
178 stars 8 forks source link

绑定 scroll 事件时候遇到的问题 #1

Open lishengzxc opened 8 years ago

lishengzxc commented 8 years ago

以前一直用iScroll这一方案来处理移动端的滚动,这次需要做 PC 上做一个滚动加载更多的功能,因为是 PC 就考虑不用iScroll了,然后用 Dash 查了下 scroll,看到了以下例子

<!DOCTYPE html>
<html lang="en">
  <head>
  <meta charset="UTF-8" />
  <style>
  #container {
    position: absolute;
    height: auto;
    top: 0;
    bottom: 0;
    width: auto;
    left: 0;
    right: 0;
    overflow: auto;
  }

  #foo {
    height:1000px;
    width:1000px;
    background-color: #777;
    display: block;
  }

  </style>
  </head>
  <body>
    <div id="container">
      <div id="foo"></div>
    </div>

    <script type="text/javascript">
      document.getElementById('container').onscroll = function() {
        console.log("scrolling");
      };
    </script>
  </body>
</html>

然后我就想当然了在document.body.onscroll附上了回调函数,结果在Chrome下偶尔会出现页面滚动,但是回调不执行的情况下。然后通过Chrome的审查元素发现,回调不成功的情况是因为回调并没有绑定上去,然后在window.addEventListener('scroll', function() {}),发现成功了。

因为自己要一个刨根问底的心,并找到了一下相关资料: http://www.w3help.org/zh-cn/causes/SD9013

所以,结论是: 请在window上绑定scroll事件