对象构造函数中滚动事件监听器失效,slideIt仅初始化执行一次的原因排查
问题原因与解决方案
嘿,我来帮你拆解下这个问题的核心原因:
1. 事件绑定错误:立即执行了方法而非传递回调
你构造函数里的这行代码是关键问题:
this.scrollable_div.scroll(this.slideIt())
这里你给scroll()方法传递的是this.slideIt()的执行结果(因为加了圆括号),而不是slideIt方法本身。这就导致初始化时会立刻调用一次slideIt,但滚动事件触发时没有任何回调函数被执行,自然没反应。
2. this指向问题(隐藏坑)
就算你去掉圆括号写成this.scrollable_div.scroll(this.slideIt),还是会有问题:jQuery事件回调里的this默认指向触发事件的DOM元素(也就是scrollable_div对应的元素),而不是你的fixed_column_or_row实例。这会导致slideIt里的this.scrollable_div、this.fixed_row等属性全部无法访问,代码会报错。
修正方案(二选一即可)
方案一:用箭头函数绑定this
箭头函数会继承外层作用域的this(也就是你的实例对象),同时不会立即执行方法:
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") // 用箭头函数包裹,确保this指向实例 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:", scrollTop) this.fixed_row.css({ "margin-left": -scrollLeft }); this.fixed_column.css({ "margin-top": -scrollTop }); }
方案二:用bind()固定this指向
bind()方法会返回一个新函数,把this强制绑定为你的实例对象:
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") // 用bind把this绑定到实例 this.scrollable_div.scroll(this.slideIt.bind(this)) } fixed_column_or_row.prototype.slideIt=function(){ var scrollTop = this.scrollable_div.scrollTop(), scrollLeft = this.scrollable_div.scrollLeft(); console.log("scrollTop:", scrollTop) this.fixed_row.css({ "margin-left": -scrollLeft }); this.fixed_column.css({ "margin-top": -scrollTop }); }
内容的提问来源于stack exchange,提问作者Sami Al-Subhi
相关产品推荐
相关产品推荐

