我的滚动事件绑定不起作用

时间:2018-08-16 23:19:34

标签: javascript jquery knockout.js

我在我的身体标签上添加了滚动绑定

<body style="" data-bind="event : { scroll: scrollingInboxMessagesBox }">

及其对应的侦听器

model.scrollingInboxMessagesBox = function (data,event) {

    var body = $('body');

    if (body.scrollTop == (body.scrollHeight - body.offsetHeight)) //scrollTop is 0 based
    {
        alert('Reached the bottom!');
    }

    console.log("body " + body.scrollHeight - body.offsetHeight);
    console.log($("body").scrollTop());

};

但是我注意到,即使我从不解雇听众,当我尝试“ mouseover”之类的其他事件时,它仍然可以工作。为什么会这样?

1 个答案:

答案 0 :(得分:0)

使用mousewheel事件代替this答案所建议的scroll

var viewModel = function(){
  var self = this;
  self.scrollingInboxMessagesBox = function (data,event) {
      //console.log('hi');
      var body = $('body')[0];

      if (body.scrollTop == (body.scrollHeight - body.offsetHeight))        //scrollTop is 0 based
      {
          alert('Reached the bottom!');
      }

      console.log("body " + (body.scrollHeight - body.offsetHeight));
      console.log($("body").scrollTop());

  };
};

ko.applyBindings(new viewModel());
body {
 height : 200vh
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body data-bind="event : { mousewheel: scrollingInboxMessagesBox }">
    </body>