大家好,我只是试图从窗口中删除此keyup事件,但它不起作用。
toggle(forceClose = false) {
const shouldClose = forceClose || this.isOpen()
const action = shouldClose ? 'remove' : 'add'
const expanded = !shouldClose
var escape = function(e) {
if (e.key === "Escape" || e.which === 27) {
console.log("Escape")
}
}
if (shouldClose && this.targetEl) {
window.removeEventListener('keyup', escape, true)
this.targetEl.classList.remove(this.options.menuActiveClass)
setTimeout(() => !this.targetEl.classList.contains(this.options.menuActiveClass) && this.targetEl.classList.remove(this.options.menuOpenClass), 300)
} else if (this.targetEl) {
window.addEventListener('keyup', escape, true)
this.targetEl.classList.add(this.options.menuOpenClass)
setTimeout(() => this.targetEl.classList.contains(this.options.menuOpenClass) && this.targetEl.classList.add(this.options.menuActiveClass), 10)
}
}发布于 2020-01-21 23:58:48
您将在每次调用时创建一个新的escape函数。因此,removeEventListener将尝试删除一些从未添加的内容。
将声明移动到外部范围
toggle(forceClose = false) {
const shouldClose = forceClose || this.isOpen()
const action = shouldClose ? 'remove' : 'add'
const expanded = !shouldClose
if (shouldClose && this.targetEl) {
window.removeEventListener('keyup', escape, true)
this.targetEl.classList.remove(this.options.menuActiveClass)
setTimeout(() => !this.targetEl.classList.contains(this.options.menuActiveClass) && this.targetEl.classList.remove(this.options.menuOpenClass), 300)
} else if (this.targetEl) {
window.addEventListener('keyup', escape, true)
this.targetEl.classList.add(this.options.menuOpenClass)
setTimeout(() => this.targetEl.classList.contains(this.options.menuOpenClass) && this.targetEl.classList.add(this.options.menuActiveClass), 10)
}
}
function escape(e) {
if (e.key === "Escape" || e.which === 27) {
console.log("Escape")
}
}发布于 2020-01-21 23:59:07
当你调用removeEventListener时,你必须在addEventListener上传递相同的实例作为函数。
因此在本例中,您必须定义换码ouside切换
https://stackoverflow.com/questions/59844797
复制相似问题