我有以下代码,现在可以使用。问题是为什么?
let resizing = false
let startX = 0
let startY = 0
window.addEventListener('mousedown', (e) => {
resizing = true
startX = e.clientX
startY = e.clientY
console.log('startX ' + startX)
document.body.addEventListener('mouseup', (e) => {
if (resizing) {
let endX = e.screenX
console.log('endX ' + endX)
let endY = e.screenY
this.resize(startX, endX, startY, endY, window)
}
resizing = false
e.target.removeEventListener('mouseup', window)
})
})
以前我在 mouseup 回调中定义了我的startX
and ,如下所示:startY
let resizing = false
window.addEventListener('mousedown', (e) => {
resizing = true
let startX = e.clientX
let startY = e.clientY
console.log('startX ' + startX)
document.body.addEventListener('mouseup', (e) => {
if (resizing) {
let endX = e.screenX
console.log('endX ' + endX)
let endY = e.screenY
this.resize(startX, endX, startY, endY, window)
}
resizing = false
e.target.removeEventListener('mouseup', window)
})
})
但是每次在第一次触发事件后,我得到相同的 startX 和 startY 值。为什么?这对我来说没有意义,因为每次 mouseup 事件的回调函数完成时,let 的范围都应该重置变量?
我根据 Taplars 评论更新了我的代码,现在范围按我的预期工作
let window = this
window.addEventListener('mousedown', (e) => {
let startX = e.clientX
let startY = e.clientY
console.log('startX ' + startX)
var mouseUpHandler = function (e) {
console.log('mouseup')
let endX = e.screenX
console.log('endX ' + endX)
let endY = e.screenY
window.resize(startX, endX, startY, endY, window)
document.body.removeEventListener('mouseup', mouseUpHandler)
}
document.body.addEventListener('mouseup', mouseUpHandler)
})
}