我使用rails7和Stimulus.js来进行滚动事件。这段代码在目标页面中效果很好。但当我移动另一页的时候。意外地影响此代码并获得错误。有人能帮我吗?
import { Controller } from '@hotwired/stimulus'
export default class extends Controller {
connect() {
window.addEventListener("scroll", function() {
const targetTitle = document.getElementById( "target_title" );
const clientHeight = targetTitle.getBoundingClientRect().top;
if (-100 > clientHeight) {
document.getElementById('scroll_header').classList.add('!block')
} else {
document.getElementById('scroll_header').classList.remove('!block')
}
});
}
}发布于 2022-10-23 12:26:25
根据你的描述,我想你也在用涡轮增压。如果是这样,那么页面就不会按照通常的方式加载,只有当前html页面的主体部分会被替换,因此,以前添加的任何事件侦听器都将保持活动状态。
当您将EventListener添加到元素时,也应该在/如果不再需要时,使用removeEventListener删除它。当控制器绑定到的元素从页面中移除时,通过调用控制器的disconnect函数,刺激使这一点变得简单(参见https://stimulus.hotwired.dev/reference/lifecycle-callbacks#disconnection)。
因此,按下面的方式更改控制器应该可以做到这一点(我没有测试这段代码,其中可能有打印错误和其他错误,但它为您提供了指向解决方案的指针)。
import { Controller } from '@hotwired/stimulus'
export default class extends Controller {
handleScroll(_event) {
const targetTitle = document.getElementById( "target_title" );
const clientHeight = targetTitle.getBoundingClientRect().top;
if (-100 > clientHeight) {
document.getElementById('scroll_header').classList.add('!block')
} else {
document.getElementById('scroll_header').classList.remove('!block')
}
}
connect() {
window.addEventListener("scroll", this.handleScroll)
}
disconnect() {
window.removeEventListener("scroll", this.handleScroll);
}
}https://stackoverflow.com/questions/74168867
复制相似问题