我无法在对象构造函数中创建一个事件监听器来监听

当我滚动 div 时,基本上什么也没发生。该方法slideIt在对象启动时被触发一次,就是这样。它不是在监听滚动事件!为什么会发生这种情况?


function fixed_column_or_row(container_name){

    this.container_div=$(container_name);


    this.scrollable_div=this.container_div.find(".simplebar-content-wrapper");

    this.fixed_row=this.container_div.find(".fixed-row")

    this.fixed_column=this.container_div.find(".fixed-column")


    //the issue in this line

    this.scrollable_div.scroll(this.slideIt())


}


fixed_column_or_row.prototype.slideIt=function(){

     var scrollTop      = this.scrollable_div.scrollTop(),

     scrollLeft      = this.scrollable_div.scrollLeft();

     console.log("scrollTop")

     this.fixed_row.css({

         "margin-left": -scrollLeft

     });


     this.fixed_column.css({

         "margin-top": -scrollTop

      }); 


}


绝地无双
浏览 225回答 1
1回答

慕侠2389804

一个常见的 JavaScript 错误是在需要引用函数时输入函数调用(通常用于设置事件处理程序,但也有其他类似的情况)。因此  this.scrollable_div.scroll(this.slideIt());会调用该this.slideIt()函数和返回值传递给.scroll方法,那显然不是什么需要。在()后this.slideIt是什么原因造成这一点,所以this.slideIt 没有 ()必要。现在,完成后,下一个问题将是 与 的关系this将丢失。Stackoverflow 上有各种各样的问题,其中有关于this工作原理的详尽而详尽的答案。 这里只想说,有必要确保this正确设置:  this.scrollable_div.scroll(this.slideIt.bind(this));(还有其他方法可以做到,但这应该可行。)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript