间隔不会清除/ clientX& /或clientY无法正常工作

时间:2016-12-12 03:12:33

标签: javascript

我正在使用dat.gui

制作一个简单的绘图程序

我有一个每50毫秒运行一次的函数,使用如下设置间隔:

window.addEventListener("mousedown", function() {
    let run = setInterval(function() {
        // function here
    }, 50)
})
window.addEventListener("mouseup", function() {
    clearInterval(run)
})

那有什么问题呢?我也遇到了clientX和clientY的麻烦。

我拥有的是:

window.addEventListener("mousedown", function() {
    let run = setInterval(function(event) {
        let x = event.clientX,
          y = event.clientY;
    }, 50)
})

我尝试过在没有事件的情况下使用它作为参数,它仍然无效。奇怪的是它适用于这样的实例:

window.addEventListener("mousemove", function() {
    let x = event.clientX,
      y = event.clientY;
}

所以我错过了什么?我试过看了这个,但没找到任何东西。我也有完整的东西:

http://codepen.io/TheAndersMan/pen/pNZwrN?editors=0011

提前致谢!

2 个答案:

答案 0 :(得分:1)

在回调函数中,您缺少传递的参数event(事件对象),并且您的run变量也应该在任一侦听器的范围之外声明。

编辑:为了跟踪鼠标的位置,您需要将事件监听器附加到mousemove事件,因此我必须添加另一个函数作为此事件处理程序,附在mousedown上并在mouseup上分离。

let run,
    x, y

window.addEventListener('mousedown', function (event) {
    run = setInterval(function() {
        console.log(x, y)
    }, 50)
    trackMouse(event)
    this.addEventListener('mousemove', trackMouse)
})

window.addEventListener("mouseup", function () {
    clearInterval(run)
    this.removeEventListener('mousemove', trackMouse)
})

function trackMouse (event) {
    x = event.clientX
    y = event.clientY
}

答案 1 :(得分:1)

window.addEventListener("mousedown", function() {
    let run = setInterval(function() {
        // function here
    }, 50)
})
window.addEventListener("mouseup", function() {
    clearInterval(run)
})

您不能在run侦听器中使用mouseup变量,因为它们是在其他范围内定义的。

您可以将event变量传递给区间:

setInterval(function(){}, 50, event);