使用rails+Stimulus.js的滚动功能在其他页面中出错



I使用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')
}
});
}
}

根据您的描述,我想您也在使用turbo。如果是这样,那么页面就不会以通常的方式加载,只会替换当前html页面的正文部分,因此,之前添加的任何事件侦听器都将保持活动状态。

当您将EventListener添加到元素中时,如果不再需要它,也应该使用removeEventListener将其删除。当控制器绑定到的元素从页面中删除时,Stimulus通过调用控制器的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);
}
}

最新更新